Python爬虫之Selenium警告框(弹窗)处理

来自:网络
时间:2021-01-13
阅读:

JavaScript 有三种弹窗 Alert (只有确定按钮), Confirmation (确定,取消等按钮), Prompt (有输入对话框),而且弹出的窗口是不能通过前端工具对其进行定位的,这个时候就可以通过switch_to.alert方法来定位这个弹窗,并进行一系列的操作。

本章中用到的关键方法如下:

switch_to.alert:定位到警告框 text:获取警告框中的文字信息 accept():接受现有警告框(相当于确认) dismiss():解散现有警告框(相当于取消) send_keys('文本内容'):发送文本至警告框(适用于有输入对话框的弹窗) click():鼠标点击事件(其他鼠标事件请参考Python爬虫 - Selenium(5)鼠标事件) move_to_element():鼠标悬停(详情请参考Python爬虫 - Selenium(5)鼠标事件)
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
driver = webdriver.Chrome()
driver.get('http://www.baidu.com')

# 鼠标悬停至“设置”链接
link = driver.find_element_by_link_text('设置')
ActionChains(driver).move_to_element(link).perform()
time.sleep(2) #睡两秒,看一下效果

# 打开搜索设置
driver.find_element_by_link_text("搜索设置").click()
time.sleep(2) #睡两秒,看一下效果

# 保存设置
driver.find_element_by_class_name("prefpanelgo").click()
time.sleep(2) #睡两秒,看一下效果

# 定位警告框
alert = driver.switch_to.alert
print(alert.text) # 打印警告框内容
#alert.send_keys('输入内容') #此测试网站不是可输入类型的弹窗,先注释掉
alert.accept() #接受现有警告框,相当于确认
#alert.dismiss() #解散现有警告框,相当于取消
time.sleep(2) #睡两秒,看一下效果

driver.quit()
返回顶部
顶部