You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 UnexpectedAlertPresentException from crashing your script.
  • Stable Element Locator: Instead of an absolute XPath, we use a relative locator targeting the button's aria-label attribute. Google's accessibility labels are far more consistent than page hierarchy.
  • Explicit Wait: Replaced time.sleep(10) with WebDriverWait, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:02:44