语境:
>我的脚本使用selenium webdriver启动到网站
>用户填写网站上的一些东西
>用户将点击一个按钮,弹出确认()dialog
box询问用户“你想提交数据吗”
我的本意:
我的脚本会等到用户点击按钮.一旦检测到用户点击了该按钮,我的脚本就会获得一个元素的值,然后(不知何故)在dialog box上单击OK.
题:
如何等待用户点击按钮?
然后如何在dialog box上单击“确定”?
补充说明:
使用:chromedriver,Python 2.7
按钮:< input id =“submitID”type =“button”class =“medium”value =“提交填充数据”>
[编辑]一些代码片段:
对话框弹出窗口是javascript弹出窗口:
if (window.confirm("Are you sure you want to submit the data?")) {
this.SaveData();
}
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
PATH_TO_CHROMEDRIVER = 'path/to/chromedriver'
URL = 'https://website-asking-user-to-fill-in-stuff.com'
driver = webdriver.Chrome(PATH_TO_CHROMEDRIVER)
driver.get(URL)
while True:
# loop until user close the chrome.
# If anyone has any better idea to
# WAIT TILL USER CLOSE THE WEBDRIVER, PLEASE SHARE IT HERE
try:
# --- main part of the code ---
waitForUserToClickButton() # this is what I need help with
driver.find_element_by_id('elementID').text
confirmJavascriptPopup() # this is also what I need help with
except WebDriverException:
print 'User closed the browser'
exit()
解决方法:
问:如何等待用户点击按钮?
在这种情况下,您可以引入webdriverwait,它在selenium中是显式等待.
您可以尝试使用以下代码:
from selenium.webdriver.support import expected_conditions as EC
wait = webdriverwait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'submitID')))
问:如何在对话框中单击“确定”?
在这种情况下,首先您必须将Web驱动程序的焦点切换到警报,然后您可以单击它.
alert = browser.switch_to.alert
alert.accept()
print("alert accepted")
更新1:
当您执行单击操作时,会弹出一个警报.您可以使用以下代码从警报中提取文本:
alert = browser.switch_to.alert
msg_from_alert = alert.text
alert.accept()
现在,您只需将其与您已知的预期消息进行匹配即可.
expected_msg = "some msg from alert"
from collections import Counter
Counter(msg_from_alert) == Counter(expected_msg)
True
原文地址:https://codeday.me/bug/20190701/1346611.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。