2013-02-19 62 views
2

試圖在python中設置一個超時,就像在ruby中一樣。在python splinter web crawler中設置一個timout

我有一個鏈接,當我點擊它時打開一個彈出窗口,但我無法訪問它,因爲它會導致腳本凍結,直到我殺死它。我一直試圖用幾個月的時間來訪問這個彈出窗口,在ruby watir-webdriver中沒有任何喜悅。

我想暫停對彈出窗口的調用,然後訪問彈出窗口。

@timeout(3) 
try: 
b.execute_script("javascript:openMdlWindow('InvestmentDetailOptions.aspx?IDAssetType=','620','600');if(window.document.RetValue == '2'){window.parent.LoadinIframe('InvestmentDetail.aspx?FromMenu=N&IDAssetType=','Investment Details > Full View','false');}") 
except Exception, e: 
print 'timeout!' 

任何幫助將深表感謝。

+0

你將不得不提供更多的情況下,你使用諸如框架。在這裏使用裝飾器也不行。在應用'timeout'之前,你必須將你的代碼封裝在一個函數中。 – 2013-02-19 01:52:39

+0

我正在使用python和splinter我試圖導航的網站是ASPX .Net。我能夠啓動彈出窗口,但之後無法訪問彈出窗口,因爲腳本只是掛起而不會繼續。我對python非常陌生,我正在努力盡可能快地閱讀。我不確定你在說什麼功能。 – user1279586 2013-02-19 02:20:26

回答

2
import signal 
from time import sleep 

class TimeoutException(Exception): 
    pass 

def do_something_else(): 
    time = 5 
    sleep(time) 
    return 'do_something_else has to run for %d seconds' % time 

def handler(signum, frame): 
    raise TimeoutException 

def do_something_with_timeout(callback, timeout=3): 
    signal.signal(signal.SIGALRM, handler) 
    signal.alarm(timeout) 
    try: 
     value = callback() 
     signal.alarm(0) 
     return value 
    except TimeoutException: 
     pass 
    signal.signal(signal.SIGALRM, signal.SIG_IGN) 
    return 'time out' 

def main(): 
    print 'hello' 
    print do_something_with_timeout(do_something_else) 
    print 'world' 

main() 
3

就試試這個:

from splinter import Browser 
from selenium.common.exceptions import TimeoutException 
b = Browser('firefox') 
b.driver.set_page_load_timeout(1) 
try: 
    b.visit('http://www.bbc.com') 
except TimeoutException: 
    pass 
print b.html