python - 在 Selenium 中处理弹出窗口

标签 python selenium authentication browser automation

我正在输入密码并检查它是否有效。 enter image description here

输入错误密码后,网站会重新加载并弹出窗口。 enter image description here

如何处理弹出窗口?例如,如何自动点击弹出窗口中的某个元素?

我的代码:

from selenium.webdriver.support import expected_conditions as EC
     while (2>1):
              Sam = browser.find_element_by_css_selector("input[id=1]")
              Sam.send_keys(i)
              login = browser.find_element_by_css_selector("input[id=2]")
              login.click()
              if EC.alert_is_present:
                   browser.switch_to.alert.accept()
              else:
                  print i
                  break;

我收到此错误:

Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    sexy()
  File "<pyshell#57>", line 3, in sexy
    browser.get('http://eps.gpeonline.co.in/')
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 264, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
WebDriverException: Message: Failed to decode response from marionette

最佳答案

您错误地使用了 EC.alert_is_present:您的 if 条件将始终返回 True,因为 EC.alert_is_present 是只是一个类。尝试使用下面的 try/ except block 代替 if/else:

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait as wait

try:
    wait(browser, 1).until(EC.alert_is_present()).accept()
except TimeoutException:
    print i
    break

这应该允许您在警报出现时接受警报,或者打印 i 并在 1 秒内未出现时中断循环(如果需要,您可以更改超时值)

关于python - 在 Selenium 中处理弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44215846/

相关文章:

python - Python 中的正则表达式匹配问题

python - 我可以在没有/usr/local 等权限的情况下使用 setuptools 吗

java - 如何使用 appium 测试聊天应用程序?

ruby-on-rails - selenium/capybara - 无法加载 Firefox 配置文件

php - DVWA登录错误

python - 计算两个矩阵的行之间的相关系数

python - 使用 Dicts 设置 DataFrame,意外设置

java - 我正在 selenium 自动化中创建页面对象模型框架,并且面临 java 空指针异常

web-services - 同一台机器 WS 调用是否仍需要 SSL/TLS

javascript - 如何做类似登录按钮的 Dropbox?