web自动化-提示框(Alerts警告框、Confirm 确认框、Prompt 提⽰框)

发布时间 2023-07-27 00:05:19作者: 琉璃星眸
 
driver.refresh()WebDriver提供了⼀个API, ⽤于处理JavaScript提供的三种类型的原⽣弹窗消息. 这些弹窗由
浏览器提供限定的样式.
 
Alerts 警告框
其中最基本的称为警告框, 它显⽰⼀条⾃定义消息, 以及⼀个⽤于关闭该警告的按钮, 在⼤多
数浏览器中标记为"确定"(OK). 在⼤多数浏览器中, 也可以通过按"关闭"(close)按钮将其关闭,
但这始终与“确定”按钮具有相同的作⽤.
WebDriver可以从弹窗获取⽂本并接受或关闭这些警告
# Click the link to activate the alert
driver.find_element(By.LINK_TEXT, "See an example alert").click()
# Wait for the alert to be displayed and store it in a variable
alert = wait.until(expected_conditions.alert_is_present())
# Store the alert text in a variable
text = alert.text
# Press the OK button
alert.accept()

 

Confirm 确认框
确认框类似于警告框, 不同之处在于⽤户还可以选择取消消息. 查看样例确认框.
此⽰例还呈现了警告的另⼀种实现:
 
# Click the link to activate the alert
driver.find_element(By.LINK_TEXT, "See a sample confirm").click()
# Wait for the alert to be displayed
wait.until(expected_conditions.alert_is_present())
# Store the alert in a variable for reuse
alert = driver.switch_to.alert
# Store the alert text in a variable
text = alert.text
# Press the Cancel button
alert.dismiss()

 

 
Prompt 提⽰框
提⽰框与确认框相似, 不同之处在于它们还包括⽂本输⼊. 与处理表单元素类似, 您可以使⽤
WebDriver的sendKeys来填写响应. 这将完全替换占位符⽂本. 按下取消按钮将不会提交任何
⽂本.
# Click the link to activate the alert
driver.find_element(By.LINK_TEXT, "See a sample prompt").click()
# Wait for the alert to be displayed
wait.until(expected_conditions.alert_is_present())
# Store the alert in a variable for reuse
alert = Alert(driver)
# Type your message
alert.send_keys("Selenium")
# Press the OK button
alert.accept()

 

alert.accept()PS:Chrome浏览器,在send_keys这个操作上存在问题,在国外知名男性交友⽹站
stackoverflow上,我找到了答案:⾸先⽕狐不存在该问题,然后⾕歌,就是⼀个显⽰的问
题,不会在⽂本框中显⽰输⼊的⽂本,实际会在点击确认警告框后,提交发送的⽂本信息