14-alert\confirm\prompt\自定义弹窗

一、认识alert\confirm\prompt

下图依次是alert、confirm、prompt,先认清楚长什么样子,以后遇到了就知道如何操作了。

二、alert操作

  1. 先用driver.switch_to.alert方法切换到alert弹出框上;
  2. 可以用text方法获取弹出的文本信息;
  3. accept()方法相当于点击"确认"按钮;
  4. dismiss()方法相当于点击右上角的x,取消弹出框。
python 复制代码
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('A.html')
time.sleep(1)

# 点击主页面上的alert按钮
driver.find_element('id', 'alert').click()
time.sleep(1)

# 切换到alert框
t = driver.switch_to.alert

# 打印alert框中的文本信息
print(t.text)

# 点击alert框中的确认按钮
t.accept()

# 相当于点右上角的x,取消弹出框。
# t.dismiss()

三、confirm操作

  1. 先用driver.switch_to.alert方法切换到confirm弹出框上;
  2. 可以用text方法获取弹出的文本信息;
  3. accept()方法相当于点击"确认"按钮;
  4. dismiss()方法相当于点击"取消"按钮。
python 复制代码
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('A.html')
time.sleep(1)

# 点击主页面上的confirm按钮
driver.find_element('id', 'confirm').click()
time.sleep(1)

# 切换到confirm框(这里用的也是driver.switch_to.alert)
t = driver.switch_to.alert

# 打印confirm框中的文本信息
print(t.text)

# 点击confirm框中的确认按钮
t.accept()

# 点击confirm框中的取消按钮
# t.dismiss()

四、prompt操作

  1. 先用driver.switch_to.alert方法切换到prompt弹出框上;
  2. 可以用text方法获取弹出的文本信息;
  3. accept()方法相当于点击"确认"按钮;
  4. dismiss()方法相当于点击"取消"按钮;
  5. 可以用send_keys()方法向prompt输入框中输入文本内容。
python 复制代码
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('A.html')
time.sleep(1)

# 点击主页面上的prompt按钮
driver.find_element('id', 'prompt').click()
time.sleep(1)

# 切换到prompt框(这里用的也是driver.switch_to.alert)
t = driver.switch_to.alert

# 打印prompt框中的文本信息
print(t.text)

# 向prompt输入框中输入文本内容
t.send_keys('我是prompt框')

# 点击prompt框中的确认按钮
t.accept()

# 点击prompt框中的取消按钮
# t.dismiss()

五、自定义弹窗

由于alert弹窗不美观,现在大多数网站都会使用自定义弹窗,使用selenium自带的方法无法处理,此时就需要通过JS代码来处理了。这里以新世界教育网为例:https://sh.xsjedu.org/riyu/zt/006/

上图中的这种蓝色弹窗就是现在主流的表现形式,处理这种弹窗可以利用JS代码进行处理,这种元素对象有一个display属性,可以设置元素是否显示。

python 复制代码
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('https://sh.xsjedu.org/riyu/zt/006/')
time.sleep(1)

js = 'document.getElementsByClassName("tanchuang")[0].style.display="none";'
driver.execute_script(js)
相关推荐
水银嘻嘻7 小时前
12 web 自动化之基于关键字+数据驱动-反射自动化框架搭建
运维·前端·自动化
程序员小远15 小时前
UI自动化测试方案详解
自动化测试·软件测试·selenium·测试工具·ui·职场和发展·测试用例
厦门辰迈智慧科技有限公司16 小时前
城市综合管廊监测与维护一体化解决方案
物联网·自动化·监测
sy_cora20 小时前
IEEE 列表会议第五届机器人、自动化与智能控制国际会议
运维·人工智能·机器人·自动化
云手机管家1 天前
CDN加速对云手机延迟的影响
运维·服务器·网络·容器·智能手机·矩阵·自动化
云手机管家1 天前
账号风控突破:云手机设备指纹篡改检测与反制技术解析
android·运维·网络协议·网络安全·智能手机·矩阵·自动化
struggle20251 天前
AgenticSeek开源的完全本地的 Manus AI。无需 API,享受一个自主代理,它可以思考、浏览 Web 和编码,只需支付电费。
人工智能·开源·自动化
北漂老男孩1 天前
ChromeDriver 技术生态与应用场景深度解析
java·爬虫·python·自动化
逸雨清风2 天前
Chrome更新到136以后selenium等自动化浏览器失效
selenium·自动化
小白学大数据2 天前
Python+Selenium爬虫:豆瓣登录反反爬策略解析
分布式·爬虫·python·selenium