学习Python中Selenium模块的基本用法(11:弹窗处理)

发布于:2025-08-31 ⋅ 阅读:(25) ⋅ 点赞:(0)

  网页中常用的弹窗包括警告框、提示框、确认框等类型(这三种弹窗的详细介绍见参考文献7),使用Selenium模块处理弹窗的话,首先要能找到弹窗,然后再获取弹窗信息或处理弹窗。
  网页中的弹窗,要么是在页面加载后或者其它触发条件下自动弹出,要么是点击按钮或链接时弹出,可以调用switch_to.alert函数获取弹窗对象,主要包括以下2种方式:
  1)通过第三方定时库,如果是页面加载后自动弹窗,则使用time.sleep函数等待数秒后调用switch_to.alert函数获取弹窗对象,如果是点击按钮或链接后弹窗,则页面加载后找到按钮或链接元素,模拟点击操作弹窗,然后调用switch_to.alert函数获取弹窗对象;
  2)调用Selenium模块的显式等待功能等待弹窗并获取弹窗对象,由于还没有学习Selenium模块的等待功能用法,本文采用第一种方式获取弹窗对象。

  弹窗对象相关的属性和函数如下表所示:

序号 名称 说明
1 text 属性,获取弹窗文本
2 accept 函数,模拟点击确定按钮
3 dismiss 函数,模拟点击取消按钮
4 send_keys 函数,向提示框的输入框输入文本

  Selenium官网帮助文档的警告框页面(参考文献8)包括上述三类弹窗,本文基于该页面验证Selenium模块的弹窗处理方式。
  首先是警告框,如下面代码所示,通过链接文本找到弹窗链接,点击链接弹窗后等待几秒再获取弹窗对象,最后模拟点击确定按钮关闭弹窗。

driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/zh-cn/documentation/webdriver/interactions/alerts/")

time.sleep(5)

element = driver.find_element(By.LINK_TEXT, "查看样例警告框")
element.click()

time.sleep(3)

alert = driver.switch_to.alert
print("弹窗内容:"+alert.text)
alert.accept()

  接着是确认框,如下面代码所示,通过链接文本找到弹窗链接,点击链接弹窗后等待几秒再获取弹窗对象,最后模拟点击取消按钮关闭弹窗。

driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/zh-cn/documentation/webdriver/interactions/alerts/")

time.sleep(5)

element = driver.find_element(By.LINK_TEXT, "查看样例确认框")
element.click()

time.sleep(3)

alert = driver.switch_to.alert
print("弹窗内容:"+alert.text)
alert.dismiss ()

  最后是提示框,如下面代码所示,通过链接文本找到弹窗链接,点击链接弹窗后等待几秒再获取弹窗对象,发送测试文本,最后模拟点击确定按钮关闭弹窗。

driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/zh-cn/documentation/webdriver/interactions/alerts/")

time.sleep(5)

element = driver.find_element(By.LINK_TEXT, "查看样例提示框")
element.click()

time.sleep(3)

alert = driver.switch_to.alert
alert.send_keys("Hello World!")
print("弹窗内容:"+alert.text)

time.sleep(3)

alert.accept()

参考文献:
[1]https://www.selenium.dev/zh-cn/
[2]https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/
[3]https://blog.csdn.net/kk_lzvvkpj/article/details/148610502
[4]https://registry.npmmirror.com/binary.html?path=chromedriver/
[5]https://chromedriver.chromium.org/
[6]https://blog.csdn.net/bbppooi/article/details/146242954
[7]https://blog.p2hp.com/archives/9158
[8]https://www.selenium.dev/zh-cn/documentation/webdriver/interactions/alerts/


网站公告

今日签到

点亮在社区的每一天
去签到