如何设置Selenium Python WebDriver的默认超时时间?

75

尝试找到一种好的方法来设置Selenium Python WebDriver中命令执行延迟的最大时间限制。理想情况下,像这样:

my_driver = get_my_driver()
my_driver.set_timeout(30) # seconds
my_driver.get('http://www.example.com') # stops / throws exception when time is over 30     seconds

我希望它能够起作用。我已经发现了.implicitly_wait(30),但我不确定它是否会产生期望的行为。

如果有用的话,我们特别使用Firefox的WebDriver。

编辑

根据@amey的答案,这可能会有用:

ff = webdriver.Firefox()
ff.implicitly_wait(10) # seconds
ff.get("http://somedomain/url_that_delays_loading")
myDynamicElement = ff.find_element_by_id("myDynamicElement")

然而,我不确定隐式等待是否适用于 get(这是期望的功能)和 find_element_by_id

非常感谢!


1
我查看了源代码。对于Python绑定来说,它很模糊。但是对于C#,“ImplicitlyWait”仅适用于“FindElement / FindElements”(Java也是如此)。来源:[1](https://code.google.com/p/selenium/source/browse/dotnet/src/WebDriver/ITimeouts.cs#48)[2](https://code.google.com/p/selenium/issues/detail?id=5092) - Yi Zeng
谢谢。如果您有兴趣,可以查看下面的答案。 - Juan Carlos Coto
4个回答

137

在Python中,创建页面加载超时的方法是:

Firefox、Chromedriver和undetected_chromedriver

driver.set_page_load_timeout(30)

其他:

driver.implicitly_wait(30)

如果页面加载时间超过30秒,就会抛出 TimeoutException 异常。


set_page_load_timeout 对于我的 ChromeDriver 75 版本有效。 - Stoopkid
这在Python 3.7.4、selenium 3.141.0和gecko 0.26.0中失败。 - miguelmorin

9
最好的方法是设置偏好设置:
fp = webdriver.FirefoxProfile()
fp.set_preference("http.response.timeout", 5)
fp.set_preference("dom.max_script_run_time", 5)
driver = webdriver.Firefox(firefox_profile=fp)

driver.get("http://www.google.com/")

@ivan_bilan:如果你指的是“异常”,那么不,它不返回任何内容。 - Nima Soroush
dom.max_script_run_time设置执行JavaScript的超时时间。它不是完整的页面加载超时时间。 - Corey Goldberg
这在Python 3.7.4,selenium 3.141.0和gecko 0.26.0中失败。 - miguelmorin

7

关于显式和隐式等待的信息可以在这里找到。

更新

在Java中,我看到了基于这个

WebDriver.Timeouts pageLoadTimeout(long time,
                                 java.util.concurrent.TimeUnit unit)

Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

Parameters:
    time - The timeout value.
    unit - The unit of time.

不确定Python的等价语句。


5

我的解决方案是在浏览器加载事件旁边运行一个异步线程,并在超时时关闭浏览器并重新调用加载函数。

#Thread
def f():
    loadStatus = true
    print "f started"
    time.sleep(90)
    print "f finished"
    if loadStatus is true:
        print "timeout"
        browser.close()
        call()

#Function to load
def call():
    try:
        threading.Thread(target=f).start()
        browser.get("http://website.com")
        browser.delete_all_cookies()
        loadStatus = false
    except:
        print "Connection Error"
        browser.close()
        call()

Call() 是一个函数,它只是


1
你的递归函数缺少一个在网站离线时跳出的终止条件。如果这是有意为之,请使用一个带有成功时break的无限循环。 - Git.Coach
很好的通用解决方案,无需涉及Selenium相关内容。 - user26742873

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接