我运行了几千行Python代码,调用Selenium来进行Web解析。我刚开始使用driver.refresh(),这是一种创建用户可以接受或拒绝的“警报”消息的方法。我接受以下代码行的提醒:
driver.refresh()
time.sleep(1)
#refresh loads alert; switch focus to that alert
alert = driver.switch_to_alert()
alert.accept()
但是alert.accept()行(在冗长的代码中是第913行)产生以下Traceback:
Traceback (most recent call last):
File "2.7.4__next__page__test.py", line 44, in __call__
return self._func(*args)
File "2.7.4__next__page__test.py", line 1202, in startapi
loggingvariableprovided)
File "2.7.4__next__page__test.py", line 913, in query_literature_online_master_function
alert.accept()
File "c:\python27\lib\site-packages\selenium-2.37.2-py2.7.egg\selenium\webdriver\common\alert.py", line 54, in accept
self.driver.execute(Command.ACCEPT_ALERT)
File "c:\python27\lib\site-packages\selenium-2.37.2-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 164, in execute
self.error_handler.check_response(response)
File "c:\python27\lib\site-packages\selenium-2.37.2-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 164, in check_response
raise exception_class(message, screen, stacktrace)
WebDriverException: Message: u'a is null' ; Stacktrace:
at fxdriver.modals.findButton_ (file:///c:/users/douglas/appdata/local/temp/tmpco7fll/extensions/fxdriver@googlecode.com/components/driver_component.js:8443)
at fxdriver.modals.acceptAlert (file:///c:/users/douglas/appdata/local/temp/tmpco7fll/extensions/fxdriver@googlecode.com/components/driver_component.js:8414)
at FirefoxDriver.prototype.acceptAlert (file:///c:/users/douglas/appdata/local/temp/tmpco7fll/extensions/fxdriver@googlecode.com/components/driver_component.js:9111)
at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/douglas/appdata/local/temp/tmpco7fll/extensions/fxdriver@googlecode.com/components/command_processor.js:10851)
at fxdriver.Timer.prototype.setTimeout/<.notify (file:///c:/users/douglas/appdata/local/temp/tmpco7fll/extensions/fxdriver@googlecode.com/components/command_processor.js:396)
我正在运行Windows 8.1,Python 2.7,Selenium 2.37.2和Firefox 23 Portable。有谁知道这个错误信息意味着什么,以及我可以做些什么来解决这个问题?我会很感激别人可以提供的任何建议。
解决方案 @Jason的回复让我从previous SO answer获得了以下代码,这解决了我的问题:
try:
WebDriverWait(driver, 3).until(expected_conditions.alert_is_present(),
'Timed out waiting for PA creation ' +
'confirmation popup to appear.')
alert = driver.switch_to_alert()
alert.accept()
print "alert accepted"
except TimeoutException:
print "no alert"
答案 0 :(得分:1)
嗯,WebDriverException
最后带有javascript回溯意味着它来自浏览器端。 a
可能是警报的引用。 selenium Alert
包装器类不进行任何检查,它只是向浏览器发送命令。可能警报不会很快到来。您可以等待更长时间,或者捕获异常并再试一次,或者尝试检查警报是否先出现。
答案 1 :(得分:0)
尝试切换到Active Element,然后发送{ENTER} 它将在C#中完成,如下所示:
driver.SwitchTo().ActiveElement();
System.Windows.Forms.SendKeys.SendWait(@"{ENTER}");