2013-07-08 53 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() 

調用()是剛剛

相關問題