处理Selenium中的弹出窗口

时间:2017-05-27 10:40:09

标签: 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

1 个答案:

答案 0 :(得分:1)

您错误地使用EC.alert_is_presentif条件将始终返回True,因为EC.alert_is_present只是一个类。尝试使用try / except块而不是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秒钟内出现则中断循环(如果需要,你可以更改超时值)