在Selenium中无法找到元素时如何设置默认异常处理程序?
我经常遇到这样的情况:我的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()
呢?
1 个回答
4
<UPDATE>
首先,可以考虑使用隐式等待,因为这个问题通常发生在页面上的JavaScript触发元素出现时。在DOM准备好和JavaScript函数或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)