使用爬虫过程中,处理目标网站的警告框,并选择确认。switch_to.alert 和 alert_is_present
一、switch_to.alert
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://gsxt.gdgs.gov.cn/')
time.sleep(1)
# 隐式等待(页面加载较慢情况下,可以使用,来确保页面加载完毕)
driver.implicitly_wait(10)
# 打印网页title
# print(driver.title)
# 处理警告框
alert = driver.switch_to.alert
alert.accept() #接受现有警告框,相当于确认
# 关闭驱动
# driver.quit()
虽然上述方法确实可以处理弹出的警告框,但如果突然有一天打开这个网站时警告框没有了,switch_to.alert这段代码就会报错。
处理警告框的部分,采用alert_is_present,可以先判断是否有警告框,再进行处理。
二、alert_is_present
from selenium.webdriver.support import expected_conditions as EC
# 处理警告框
# 判断是否有警告框,有就接受
result = EC.alert_is_present()(driver)
if result:
result.accept()