如何使用Python+Selenium处理Chrome的"离开网站?更改可能未保存"弹窗
解决Selenium Chrome中"Leave site?"弹窗的问题
方法1:主动捕获并处理弹窗
点击跳转按钮后弹窗会触发,你可以通过捕获异常或主动切换到弹窗的方式确认离开:
方式A:用异常捕获处理
from selenium.common.exceptions import UnexpectedAlertPresentException # 点击跳转按钮 driver.find_element(By.XPATH, '你的跳转按钮XPATH').click() try: # 尝试执行后续元素定位 element = driver.find_element(By.XPATH, '//*[@id="repo-content-pjax-container"]/react-app/div/div/div[1]/div/div/main/div[2]/div/div[3]/div[1]/div[1]/div/div[2]/span[2]/input') except UnexpectedAlertPresentException: # 切换到弹窗并确认离开 driver.switch_to.alert.accept() # 处理完弹窗后重新执行元素定位 element = driver.find_element(By.XPATH, '//*[@id="repo-content-pjax-container"]/react-app/div/div/div[1]/div/div/main/div[2]/div/div[3]/div[1]/div[1]/div/div[2]/span[2]/input')
方式B:直接处理已知弹窗
因为你明确点击按钮后会弹出提示,可以直接处理:
# 点击跳转按钮 driver.find_element(By.XPATH, '你的跳转按钮XPATH').click() # 短延时确保弹窗加载(可选) import time time.sleep(0.5) # 确认离开弹窗 driver.switch_to.alert.accept() # 继续执行后续元素操作 element = driver.find_element(By.XPATH, '//*[@id="repo-content-pjax-container"]/react-app/div/div/div[1]/div/div/main/div[2]/div/div[3]/div[1]/div[1]/div/div[2]/span[2]/input')
方法2:通过Chrome选项禁用弹窗提示
如果不需要这类确认弹窗,可以在启动浏览器时直接配置参数禁用:
from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() # 禁用页面重新提交时的提示弹窗 chrome_options.add_argument("--disable-prompt-on-repost") # 同时禁用各类JS弹窗(可选) chrome_options.add_experimental_option("prefs", { "profile.default_content_setting_values.notifications": 2, "profile.default_content_setting_values.popups": 2 }) # 带配置启动Chrome driver = webdriver.Chrome(options=chrome_options)
问题原因说明
你遇到的UnexpectedAlertPresentException,是因为弹窗出现后浏览器焦点转移到弹窗上,Selenium无法继续定位页面元素,必须先处理弹窗才能恢复正常操作。
内容的提问来源于stack exchange,提问作者bodoed
相关产品推荐
相关产品推荐

