无法在硒中找到元素时设置默认异常处理程序?
作者:互联网
我的Selenium脚本经常会运行,然后突然崩溃并出现错误:
<class 'selenium.common.exceptions.NoSuchElementException'>
Message: u'Unable to locate element: {"method":"id","selector":"the_element_id"}'
<traceback object at 0x1017a9638>
如果我以交互方式运行(python -i myseltest.py),那么我只需执行以下操作即可:
driver.switch_to_window(driver.window_handles[0])
然后再次运行特定的find_element_by_id(),它将成功.
如果发生异常,是否可以自动尝试进行driver.switch_to_window()调用?
解决方法:
< UPDATE>
首先,考虑使用implicit wait,因为此问题主要发生在页面上的javascript触发元素的存在时,并且DOMReady事件和js函数或ajax查询执行之间可能会延迟几秒钟.
< / UPDATE>
这个?
from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
class MyFirefox(Firefox):
RETRIES = 3
TIMEOUT_SECONDS = 10
def find_element_by_id(self, id):
tries = 0
element = None
while tries < self.RETRIES:
try:
element = WebDriverWait(self, self.TIMEOUT_SECONDS).until(
lambda browser: super(MyFirefox, browser).find_element_by_id(id)
)
except TimeoutException:
tries = tries + 1
self.switch_to_window(self.window_handles[0])
continue
else:
return element
raise NoSuchElementException("Element with id=%s was not found." % id)
标签:selenium-rc,selenium,selenium-webdriver,exception-handling,python 来源: https://codeday.me/bug/20191201/2083161.html