重写Python Selenium WebDriver.get()以捕获TimeoutException

时间:2019-06-17 17:45:05

标签: python selenium

我正在将Python Selenium与Chromedriver结合使用。有时,webdriver.get()调用会抛出TimeoutException。我通过显式等待成功捕获了所有其他异常,但是TimeoutException似乎是在网络流丢失时发生的。

我想做的是修改webdriver.get()方法(通过覆盖或子类化),以便每次我的应用程序调用{​​{1}}时,它都会自动:

  • 捕获并处理get()
  • 重试TimeoutException请求几次

我如何做到这一点?

注意:这个问题不是How to set the timeout of 'driver.get' for python selenium 3.8.0?的重复-我正在尝试向get()方法添加隐式功能。我之所以不将我的get()调用手动包装在try / except块中,是因为我要遍历我的应用程序并试图使其变干。

2 个答案:

答案 0 :(得分:0)

我认为最好的方法是进行try / except并使except仅捕获TimeOutException

from selenium.common.exceptions import TimeoutException
try:
    webdriver.get(url)
except TimeoutException:
    time.sleep(5)
    webdriver.get(url)

如果问题是您必须多次将其封装在一个方法中

答案 1 :(得分:0)

我知道了。您必须像这样子化EventFiringWebDriver

from selenium.support.events import EventFiringWebDriver

class MyWebDriver(EventFiringWebDriver):
    def get( self ,url):
        try:
            super().get(url)
        except TimeoutException:
            # your exception handling code goes here