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

Jua*_*oto 39 python firefox selenium timeout selenium-webdriver

试图找到一种在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
Run Code Online (Sandbox Code Playgroud)

会工作.我发现了.implicitly_wait(30),但我不确定它是否会导致所需的行为.

如果它有用,我们专门使用WebDriver for Firefox.

编辑

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

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

但是,我不清楚隐式等待是否适用于get(这是所需的功能)和find_element_by_id.

非常感谢!

Jua*_*oto 85

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

driver.set_page_load_timeout(30)
Run Code Online (Sandbox Code Playgroud)

对于chromedriver:

driver.implicitly_wait(30)
Run Code Online (Sandbox Code Playgroud)

TimeoutException每当页面加载超过30秒时,这将抛出一个.

  • 这不适用于Chrome驱动程序. (5认同)

Ame*_*mey 5

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

UPDATE

在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.
Run Code Online (Sandbox Code Playgroud)

不确定python等价物.


Nim*_*ush 5

最好的方法是设置首选项:

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/")
Run Code Online (Sandbox Code Playgroud)


小智 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()
Run Code Online (Sandbox Code Playgroud)

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