【问题标题】:How to set Selenium Python WebDriver default timeout?如何设置 Selenium Python WebDriver 默认超时?
【发布时间】:2013-07-06 03:53:50
【问题描述】:

试图找到一种在 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

非常感谢!

【问题讨论】:

  • 我查看了源代码。对于 python 绑定来说是模糊的。但对于 C#,ImplicitlyWait 仅适用于 FindElement/FindElements(对于 Java 也是如此)。来源:12
  • 谢谢。如果您有兴趣,请参阅下面的答案。

标签: python firefox selenium timeout selenium-webdriver


【解决方案1】:

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

更新

在java中我看到了这个,基于this

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 等价物。

【讨论】:

    【解决方案2】:

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

    Firefox 和 Chrome 驱动程序

    driver.set_page_load_timeout(30)
    

    其他:

    driver.implicitly_wait(30)
    

    每当页面加载时间超过 30 秒时,这将引发 TimeoutException

    【讨论】:

    • set_page_load_timeout 为我在 chromedriver 75 中工作
    • 这在 Python 3.7.4、selenium 3.141.0 和 gecko 0.26.0 上失败。
    【解决方案3】:

    最好的方法是设置偏好:

    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:如果你的意思是Exeption,不,它不会返回任何内容
    • dom.max_script_run_time 设置执行 javascript 的超时时间。这不是完整的页面加载超时。
    • 这在 Python 3.7.4、selenium 3.141.0 和 gecko 0.26.0 上失败。
    【解决方案4】:

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

    #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() 是一个函数,它只是

    【讨论】:

    • 如果网站离线,您的递归缺少中断条件。如果有意,请在成功时使用带有break 的无限循环。
    • 不错的通用解决方案,无需接触硒。
    猜你喜欢
    • 2012-04-01
    • 2015-02-10
    • 1970-01-01
    • 2017-12-25
    • 2012-05-23
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多