импортировать ОС
время импорта
import pyautogui # Для имитации действий клавиатуры
import pyperclip # Для доступа к буферу обмена
запросы на импорт # Для загрузки изображенияиз импорта селена webdriver
из selenium.webdriver.common.by импортировать Автор
из selenium.webdriver.common.action_chains импортировать ActionChains
из службы импорта selenium.webdriver.chrome.service
из selenium.webdriver.support.ui импортировать WebDriverWait
из selenium.webdriver.support импортировать ожидаемые_условия как EC
из webdriver_manager.chrome импортировать ChromeDriverManager
import uuid # Для создания уникальных имен файлов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}")
Код: Выделить всё
"""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}")
Код: Выделить всё
# 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()
search_url = "https://www.google.com/search?as_st=y&a ... tbs=&udm=2"< /p>
automate_chrome_search(search_url)
Я хочу, чтобы он автоматически открывал боковую панель изображения, подождите 15 секунд, прежде чем закрыть правую кнопку мыши, после того, как бот щелкнул правой кнопкой мыши, он должен прокрутить вниз, скопировать адрес изображения, чтобы изображение начинает загружаться, но это происходит только в том случае, если контекстное меню первого изображения не открывается для второго изображения
Подробнее здесь: https://stackoverflow.com/questions/793 ... -2nd-image
Мобильная версия