Python Selenium等待用户单击按钮 [英] Python Selenium Wait for user to click a button
问题描述
上下文:
- 我的脚本使用Selenium Webdriver启动到网站上
- 用户在网站上填写了一些内容
- 用户将单击一个按钮,该按钮将弹出一个
confirm()
对话框 框 询问用户您是否要提交数据"
- My script launch to a website using selenium webdriver
- The user fills in some stuff on the website
- The user will click a button which will popup a
confirm()
dialog box asking the user "Do you want to submit the data"
我的意图:
我的脚本将一直等到用户单击按钮.一旦检测到用户单击了按钮,我的脚本将获取一个元素的值,然后(以某种方式)在
My script would wait till the user click the button. Once it detects that the user clicked the button, my script would get a value of an element and then (somehow) click OK on the dialog box.
问题:
如何等待用户单击按钮?
然后我该如何在对话框上单击确定"?
How do I then click OK on the dialog box?
附加说明:
使用:chromedriver,Python 2.7
Using: chromedriver, Python 2.7
按钮:<input id="submitID" type="button" class="medium" value="Submit filled Data">
一些代码段:
对话框弹出窗口是javascript弹出窗口:
The dialog popup is javascript popup:
if (window.confirm("Are you sure you want to submit the data?")) {
this.SaveData();
}
我的代码(对此问题进行了简化和修改):
My code (simplified & modified for this question):
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()
推荐答案
问:如何等待用户单击按钮?
Q: How do wait for the user to click the button?
在这种情况下,您可以引入WebDriverWait
,这是硒中的显式等待.
In this case , you can introduce WebDriverWait
which is explicit wait in 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')))
问然后如何在对话框上单击确定"?
Q. How do I then click OK on the dialog box?
在这种情况下,您首先必须将Web驱动程序的焦点切换到警报,然后才能单击它.
In this case first you would have to switch the focus of your web driver to the alert and then you can click on it.
alert = browser.switch_to.alert
alert.accept()
print("alert accepted")
更新1:
当您执行单击操作时,将弹出一个警报.您可以使用以下代码从警报中提取文本:
When you are performing the click operation then there is one alert gets popped up. You can extract the text from the alert using this code :
alert = browser.switch_to.alert
msg_from_alert = alert.text
alert.accept()
现在,您只需将其与您已经知道的预期消息匹配即可.
Now You can simply match it with your expected message which is already known to you.
expected_msg = "some msg from alert"
from collections import Counter
Counter(msg_from_alert) == Counter(expected_msg)
True
这篇关于Python Selenium等待用户单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!