posted on Apr, 9 2023 @ 12:36 PM
ChatGPT3.5 has been helping me with some code for this mini-project.
In fact, I outlined the project and it generated a first draft of all the code. That code didn't quite work, but ChatGPT has also helped with some
debugging. The code now runs - up to a point. I think one element is slightly out of date (the XPATH id for the "search by image" button on the
Google Image Search website).
Here's the current version of the relevant Python code:
import os
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Set up the webdriver for Google Chrome
driver = webdriver.Chrome()
# Define the path to the folder containing the photographs to be searched
folder_path = 'E:\temp\reverse'
# Loop through each file in the specified folder
for filename in os.listdir(folder_path):
# Skip non-image files
if not filename.endswith(('.jpg', '.jpeg', '.png')):
continue
# Load the Google Images page and enter the image URL
driver.get('https://images.google.com/')
try:
# Wait until the "I agree" button is clickable
agree_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "L2AGLb")))
agree_button.)
time.sleep(3)
# Click on the "Search by image" button
search_image_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='H6eFf']")))
search_image_button.)
time.sleep(3)
# Click on the "Upload an image" option
upload_image_option = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="qbba"]/span[2]')))
upload_image_option.)
time.sleep(3)
# Find the search box element on the webpage
search_box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="qbfile"]')))
image_path = os.path.join(folder_path, filename)
search_box.send_keys(image_path)
time.sleep(3)
# Click on the "Search" button
search_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="qbbtc"]/span[2]')))
search_button.)
time.sleep(3)
# Wait for the search results to load
search_results = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'islrg')))
time.sleep(3)
# Take a screenshot of the search results and save it with the same filename as the photo but with a suffix
name, ext = os.path.splitext(filename)
screenshot_name = name + '_search results.jpeg'
driver.save_screenshot(os.path.join(folder_path, screenshot_name))
except:
print(f"Failed to search for image [filename]")
# Clean up the webdriver
driver.quit()