【问题标题】:Handling javascript dialog box on Selenium Python在 Selenium Python 上处理 javascript 对话框
【发布时间】:2017-09-04 12:25:06
【问题描述】:

我正在使用 Python 上的 Selenium webdriver 为网页编写自动化代码。但是,在某个时候,它会要求验证码。因此,我决定使用弹出的 javascript 对话框手动输入验证码。但是我的代码的问题是,为了成功实现,它使用等待并在等待()之后自动接受警报框。而且,如果我在输入验证码后按 Enter,则会引发此错误

selenium.common.exceptions.UnexpectedAlertPresentException

这是我的代码 -

def captcha():
    driver.execute_script("var a = prompt('Enter Captcha', '');document.body.setAttribute('data-id', a)")
    time.sleep(7)
    driver.switch_to.alert.accept()
    driver.find_element_by_id("captcha_code").send_keys(driver.find_element_by_tag_name('body').get_attribute('data-id'))
    driver.find_element_by_id("captcha_code").send_keys(Keys.RETURN)

为了改进它,我尝试了这段代码,其中 while 循环 每秒检查是否存在警报框,但它不起作用。

def captcha():
    driver.execute_script("var a = prompt('Enter Captcha', '');document.body.setAttribute('data-id', a)")
    while EC.alert_is_present():
        time.sleep(1)
        print("Alert Present")
        try:
            driver.switch_to.alert.accept()
        except selenium.common.exceptions.NoAlertPresentException:
            print("Error Encountered...")
            continue
        driver.find_element_by_id("captcha_code").send_keys(driver.find_element_by_tag_name('body').get_attribute('data-id'))
        driver.find_element_by_id("captcha_code").send_keys(Keys.RETURN)

它总是打印 -

提示存在

即使我没有警告框,也会继续打印很长时间。

【问题讨论】:

  • 您使用的是 Chrome 还是 Firefox?
  • 我正在使用 Chrome 网络驱动程序。

标签: javascript python selenium modal-dialog alert


【解决方案1】:

改变

while EC.alert_is_present():

while EC.alert_is_present()(driver) :

EC.alert_is_present() 返回一个函数,所以它总是评估为真

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    相关资源
    最近更新 更多