2013-07-08 93 views
27

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

会工作。我发现.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) –

+0

谢谢。如果您有兴趣,请参阅下面的答案。 –

回答

64

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

driver.set_page_load_timeout(30) 

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

+2

这不适用于Chrome驱动程序。 – sorin

+1

关心创业更多信息或进行编辑? –

4

有关显式和隐式等待的信息可以找到here

UPDATE

在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. 

不知道蟒蛇当量。

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

它会返回某种错误吗? –

+0

@ivan_bilan:如果你的意思是'Exeption',否,它不会返回任何 –

+0

'dom.max_script_run_time'设置执行javascript的超时时间。这不是一个完整的页面载入超时。 –

1

我的解决办法是运行一个异步线程旁边的浏览器加载事件,并将其关闭浏览器,然后重新调用加载功能,如果有一个时间到。

#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() 

调用()是刚刚

相关问题