Python Selenium等待用户单击按钮
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python Selenium等待用户单击按钮,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2074字,纯文字阅读大概需要3分钟。
内容图文
![Python Selenium等待用户单击按钮](/upload/InfoBanner/zyjiaocheng/782/2771c45713784768b813928425ba5e1c.jpg)
语境:
>我的脚本使用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
内容总结
以上是互联网集市为您收集整理的Python Selenium等待用户单击按钮全部内容,希望文章能够帮你解决Python Selenium等待用户单击按钮所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。