Selenium Python循环第二次执行时跳过Google Cookies弹窗及UnexpectedAlertPresentException错误排查问询
Got it, let's break down why you're hitting that UnexpectedAlertPresentException and fix your script properly.
The Root of the Problem
Your current code only catches TimeoutException, but the error you're seeing means an unhandled alert popup is appearing on the page (not just the missing cookies button). Additionally, your absolute XPath is extremely fragile—Google frequently tweaks its page structure, so that path will break easily. Plus, using a fixed window index (window_handles[2]) is risky if the number of open windows changes between runs.
Step-by-Step Fix
Here's a revised version of your function that addresses all these issues:
1. First, Import Required Helpers
Make sure you have these imports at the top of your script:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import ( TimeoutException, UnexpectedAlertPresentException, NoAlertPresentException )
2. Revised get_image Function
def get_image(title): # Open a new window and switch to it (use the latest window instead of fixed index) driver.execute_script("window.open('');") driver.switch_to.window(driver.window_handles[-1]) driver.get('https://www.google.com/imghp?hl=EN') # Handle any unexpected alerts first (this fixes your main error) try: alert = driver.switch_to.alert alert.dismiss() # Or use alert.accept() if needed print("Closed unexpected alert popup") except NoAlertPresentException: pass # No alert to handle, proceed # Wait for and handle the cookies popup (if it exists) wait = WebDriverWait(driver, 10) try: # Use a stable, relative locator instead of absolute XPath accept_cookies_btn = wait.until( EC.element_to_be_clickable( (By.XPATH, "//button[contains(@aria-label, 'Accept all')]") ) ) accept_cookies_btn.click() print("Successfully accepted cookies") except TimeoutException: print("Cookies popup not found—skipping acceptance step") # Rest of your script logic goes here...
Key Improvements Explained
- Alert Handling: We explicitly check for and close any unhandled alerts first, which prevents the
UnexpectedAlertPresentExceptionfrom crashing your script. - Stable Element Locator: Instead of an absolute XPath, we use a relative locator targeting the button's
aria-labelattribute. Google's accessibility labels are far more consistent than page hierarchy. - Explicit Wait: Replaced
time.sleep(10)withWebDriverWait, which waits up to 10 seconds for the button to be clickable. This is faster and more reliable than hardcoding sleep times. - Safe Window Switching: Using
window_handles[-1]targets the most recently opened window, avoiding issues if the number of open windows varies between runs.
Bonus Tip
If you want to make the locator even more reliable, you can use the button's text directly (note that this depends on the page language):
(By.XPATH, "//div[text()='Accept all']/parent::button")
This will work as long as the button text stays consistent, which it does for Google's cookies prompt in English.
内容的提问来源于stack exchange,提问作者Lubaba Ell

