Python Selenium等待用户单击按钮

时间:2018-08-03 23:50:26

标签: python selenium button selenium-webdriver click

上下文:

  1. 我的脚本使用Selenium Webdriver启动到网站上
  2. 用户在网站上填写了一些内容
  3. 用户将单击一个按钮,该按钮将弹出confirm() dialog box ,询问用户“您是否要提交数据”

我的意图:

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


问题:

如何等待用户单击按钮?

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


附加说明:

使用:chromedriver,Python 2.7

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


[EDIT]一些代码段:

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

2 个答案:

答案 0 :(得分:3)

问:如何等待用户单击按钮?

在这种情况下,您可以引入WebDriverWait,这是硒中的显式等待

您可以尝试使用此代码

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

答案 1 :(得分:1)

这是我设计的一个解决方案,可能并不适合所有人。轮询网址...

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

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

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