[Python] Why does the context menu fails to open for the 2nd image

Discussão em 'Python' iniciado por Stack, Janeiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    Why does the context menu doesn't open for 2nd image ,

    import os

    import time

    import pyautogui # For simulating keyboard actions

    import pyperclip # For clipboard access

    import requests # For downloading the image

    from selenium import webdriver

    from selenium.webdriver.common.by import By

    from selenium.webdriver.common.action_chains import ActionChains

    from selenium.webdriver.chrome.service import Service

    from selenium.webdriver.support.ui import WebDriverWait

    from selenium.webdriver.support import expected_conditions as EC

    from webdriver_manager.chrome import ChromeDriverManager

    import uuid # For generating unique file names

    def download_image(url, save_folder="downloaded_images"):

    """Function to download the image from the given URL."""

    try:

    # Make a request to get the image content

    response = requests.get(url, stream=True)

    response.raise_for_status() # Raise an error for bad status codes



    # Ensure the save folder exists

    os.makedirs(save_folder, exist_ok=True)



    # Use the last part of the URL as the image name

    image_name = url.split("/")[-1]

    save_path = os.path.join(save_folder, image_name)



    # Save the image content to a file

    with open(save_path, 'wb') as file:

    for chunk in response.iter_content(1024):

    file.write(chunk)



    print(f"Downloaded image saved as: {save_path}")



    except Exception as e:

    print(f"Error downloading image: {e}")


    def select_and_process_image(driver, image, wait, save_folder="downloaded_images"):

    """Selects the image, opens it, and downloads the high-quality version."""

    try:

    # Click the image to open the side panel

    image.click()

    print(f"Clicked on an image")



    # Wait for the side panel to open and ensure that the high-res image is present

    wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'sFlh5c'))) # Wait until the high-res image is present



    # Short delay to ensure the image is fully loaded

    time.sleep(5) # Wait for 5 seconds to allow the image to load



    # Find the high-quality image in the side panel

    high_quality_image = driver.find_element(By.CLASS_NAME, 'sFlh5c')



    # Simulate right-click to trigger the context menu on the high-quality image

    actions = ActionChains(driver)

    actions.context_click(high_quality_image).perform() # Right-click on the image



    # Wait for the context menu to appear

    time.sleep(1) # Small delay for the context menu to show up



    # Navigate the menu to select the "Copy image address" option (which is 10th in this case)

    for _ in range(10): # Press down 9 times to reach the "Copy image address"

    pyautogui.press('down')

    time.sleep(0.1) # Small delay to allow proper navigation in the menu



    pyautogui.press('enter') # Press Enter to copy the URL to the clipboard

    time.sleep(1) # Allow time for the clipboard action



    # Now get the copied URL from the clipboard

    image_url = pyperclip.paste() # Get the copied URL from the clipboard



    if image_url:

    print(f"Image URL: {image_url}")

    # Download the image

    download_image(image_url, save_folder)

    else:

    print("No valid URL found for this image.")



    except Exception as e:

    print(f"An error occurred while processing the image: {e}")


    def automate_chrome_search(url, save_folder="downloaded_images"):

    # Ensure the save folder exists

    os.makedirs(save_folder, exist_ok=True)



    # Set up Chrome driver

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))



    try:

    driver.get(url)



    # Wait for images to load and find all images with class 'H8Rx8c'

    wait = WebDriverWait(driver, 15)

    images = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'H8Rx8c'))) # Wait for all images



    # Loop through all found images

    for index, image in enumerate(images):

    select_and_process_image(driver, image, wait, save_folder)



    # Optionally, wait for a short time before processing the next image (if needed)

    time.sleep(2)



    # After processing, re-fetch the updated list of images for the next iteration

    images = driver.find_elements(By.CLASS_NAME, 'H8Rx8c')



    except Exception as e:

    print(f"An error occurred while processing the search: {e}")

    finally:

    # Close the browser

    driver.quit()

    Example usage:


    search_url = "https://www.google.com/search?as_st=y&as_q=anime+pc+wallpaper+4k&as_epq=&as_oq=&as_eq=&imgsz=l&imgar=w&imgcolor=&imgtype=&cr=&as_sitesearch=&as_filetype=&tbs=&udm=2"

    automate_chrome_search(search_url)

    I want it to automatically open image side panel wait 15 secs before right close clicking after the bot has right clicked it should scroll down copy image address so the the image start downloading but it only happens the first image context menu doesn't open for 2nd image

    Continue reading...

Compartilhe esta Página