3

这是很常见的情况,我的硒脚本将被运行,然后突然将与错误崩溃:无法在硒中找到元素时设置默认异常处理程序?

<class 'selenium.common.exceptions.NoSuchElementException'> 
Message: u'Unable to locate element: {"method":"id","selector":"the_element_id"}' 
<traceback object at 0x1017a9638> 

如果我在交互模式下运行(蟒蛇-i myseltest.py)如果我只是做这样的事情:

driver.switch_to_window(driver.window_handles[0]) 

,然后再次运行特定的find_element_by_id(),它会成功。

如果发生异常,有没有办法自动尝试driver.switch_to_window()调用?

回答

3

<UPDATE>
首先,可以考虑使用implicit wait,因为当元素的存在是通过对网页的JavaScript触发多发生这个问题,你可能会得到domready中的事件和JS功能或AJAX查询执行之间持续几秒钟的延迟。
</UPDATE>

This?

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) 
+0

这绝对是最好的解决方案。谢谢。 – 2012-03-07 00:33:56

相关问题