2015-01-02 58 views
0

我製作了一個使用Selenium Webdriver模塊瀏覽網站的機器人。不幸的是我注意到當腳本嘗試點擊一個按鈕時有時會停止。代碼很簡單。我嘗試點擊按鈕,如果我不能等一秒鐘再試一次。它可以工作,但在看似隨機的時間(有時在10分鐘後,有時在幾個小時後),它會在點擊按鈕後停止。防止掛起超時?

while 1: 
    try: 
     #Try to click the button 
     confirmButton = driver.find_element_by_name("confirm") 
     confirmButton.click() 
    #If we can't, wait a second and try again 
    except: 
     time.sleep(1) 

我一直在想創造一些方法來檢測這一點,從而能夠超時目前試圖點擊,但我似乎無法弄清楚如何。單線程腳本,我不能使用簡單的日期時間技術,因爲它永遠不會運行該檢查,因爲它仍然在等待按鈕完成點擊。

編輯:有人問我怎麼知道它掛着,而不是無限期地重試。我做了一個測試,在那裏我爲每一行執行了一個數字打印,當發生掛起時,它不會執行任何低於confirmButton.click()的行。我認爲這證明它是掛着的而不是無限期地重試。或者可能不是?

+0

您沒有顯示與您對腳本的描述相對應的整個代碼。在你展示的代碼中沒有再嘗試。請編輯代碼,使其與您所描述的內容相符。另外,請說明你如何知道它是*懸掛*而不僅僅是*無限期地重試*。 – Louis

+0

好的,我編輯了這篇文章。 –

回答

0

你的問題可以通過超時解決:在一個單獨的線程中啓動一個函數,如果函數沒有完成,在一定的時間限制後停止。

這裏是例子

from threading import Thread 
from time import sleep 

def threaded_function(): 
    confirmButton = driver.find_element_by_name("confirm") 
    confirmButton.click() 


if __name__ == "__main__": 
    thread = Thread(target = threaded_function) 
    thread.start() 
    thread.join(1)# this means the thread stops after 1 second, even if it is not finished yet 
    print ("thread finished...exiting") 

希望幫助,並告訴我,如果不解決的概率。

+0

我聽說過信號不能在windows上工作,當我測試它時我得到這個錯誤:AttributeError:'模塊'對象沒有屬性'SIGALRM'。你知道一種在Windows上做的方法嗎? –

+0

修復了它並簡化了代碼,以便現在很容易理解 – Gabriel