Python Selenium 等待用户点击按钮

Python Selenium Wait for user to click a button

上下文:

  1. 我的脚本使用 selenium webdriver 启动到网站
  2. 用户在网站上填写了一些东西
  3. 用户将单击一个按钮,该按钮将弹出一个 confirm()对话框 box 询问用户 "Do you want to submit the data"

我的意图:

我的脚本会等到用户单击按钮。一旦它检测到用户单击了按钮,我的脚本就会获取一个元素的值,然后(以某种方式)单击 dialog box[= 上的 OK 64=].


问题:

如何等待用户点击按钮?

如何在 dialog box 上单击“确定”?


补充说明:

使用:chromedriver,Python2.7

按钮:<input id="submitID" type="button" class="medium" value="Submit filled Data">


[编辑] 一些代码片段:

弹出的对话框是 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')))  

问。然后如何单击对话框中的“确定”?

在这种情况下,首先您必须将网络驱动程序的焦点切换到警报,然后您可以单击它。

    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

这是我设计的一个解决方案,可能并不适用于所有人。投票 URL...

poll_rate = 1
current_url = driver.current_url
while driver.current_url == current_url:
  time.sleep(poll_rate)

谁能想出更好的解决方案?!

令我震惊的是,几乎不可能以实际方式检测用户输入。

只是对我的用例的上述答案稍作修改。我设置了 30 秒 window 供用户输入密码。我的场景不需要 while 循环。

poll_rate = 30
current_url = driver.current_url
time.sleep(poll_rate)
driver.find_element(By.NAME, "verifyPassword").click()