2013-10-09 49 views
1

我以執行啓動瀏覽器的一個簡單的任務,驗證頭,並關閉瀏覽器使用Python 2.7Python的瀏覽器起動

#Launch the browser @ google 
new = 0 
url = "http://www.google.com/" 
webbrowser.open(url, new=new) 

#Check for the header 
conn = httplib.HTTPConnection("www.google.com") 
conn.request("HEAD", "/") 
r1 = conn.getresponse() 

#Close the browser 
os.system("taskkill /im iexplore.exe") 

這只是一個無限循環運行,以驗證持續連接。 Ping檢查不足以滿足我需要的流量,或者我會使用它。

我的問題是,如果我確實失去連接,腳本凍結,我得到addressinfo錯誤。我該如何忽略它,或者認識到它,終止瀏覽器並保持腳本運行?

對不起,如果我不這樣做的話......這是我的第一篇文章。

+0

你爲什麼要爲此啓動瀏覽器? – abarnert

+0

同時,你是否真的希望腳本殺死Internet Explorer的所有實例?即使用戶已將其用於其他用途?或者如果默認瀏覽器是Firefox,那麼每次調用'webbrowser.open'時都會打開Firefox? – abarnert

回答

1

我不認爲你真的需要瀏覽器在這裏。

同時,您忽略或識別錯誤的方式是使用try聲明。所以:

while True: 
    try: 
     conn = httplib.HTTPConnection("www.google.com") 
     conn.request("HEAD", "/") 
     r1 = conn.getresponse() 
     if not my_verify_response_func(r1): 
      print('Headers are wrong!') 
    except Exception as e: 
     print('Failed to check headers with {}'.format(e)) 
    time.sleep(60) # I doubt you want to run as fast as possible