微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在硒中找到元素时设置默认异常处理程序?

我的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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐