2012-11-08 29 views
0

我試圖抓住錯誤60,繼續我的腳本的執行,這裏捕獲錯誤60(超時)就是我此刻做:用的urllib 2

import urllib2 
import csv 
from bs4 import BeautifulSoup 


matcher = csv.reader(open('matcher.csv', "rb")) 

for i in matcher: 
    url = i[1] 
    if len(list(url)) > 0: 
     print url 
     try: 
      soup = BeautifulSoup(urllib2.urlopen(url,timeout=10)) 

     except urllib2.URLError, e: 
      print ("There was an error: %r" % e) 

它返回:

回溯(最近通話最後一個):文件 「debug.py」,13號線,在 湯= BeautifulSoup(urllib2.urlopen(URL,超時= 10))文件「/庫/框架/ Python的。 framework/Versions/2.7/lib/python2.7/urllib2.py「, 126行,在urlopen 返回_opener.open(URL,數據超時)文件 「/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py」, 線400,在開放 響應= self._open( req,data)File「/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py」, line 418,in _open '_open',req)File「/ Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py「, 第378行,在_call_chain result = func(* args)File」/Library/Frameworks/Python.framework/Versions/2.7/lib/ python2.7/urllib2.py「, 1207行,在http_open中 返回self.do_open(httplib.HTTPConnection,req)文件」/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2。 py「, line 1180,in do_open r = h.getresponse(buffering = True)File「/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py」, line 1030,in getresponse response.begin()File 「/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py」, 線407,在開始 版本,狀態,原因= self._read_status()文件「/庫/框架/ Python.framework/Versions/2.7/lib/python2.7/httplib.py「, line 365,in _read_status line = self.fp.readline()File」/Library/Frameworks/Python.framework/Versions/2.7/ lib/python2.7/socket.py「, line 447,in readline data = self._sock.recv(self._rbufsize)socket.timeout:timed out

我該如何捕捉這個錯誤並「繼續」?

+0

看看[這](http://stackoverflow.com/a/13275029/198633) – inspectorG4dget

回答

1

你可以嘗試except Exception as e:來捕捉所有錯誤。但是請記住,這會捕獲所有錯誤,並且如果只想捕獲特定錯誤應該避免。

編輯: 您可以通過檢查異常類型:

except Exception as e: 
    exc_type, exc_obj, exc_tb = sys.exc_info() 
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]  
    print(exc_type, fname, exc_tb.tb_lineno) 
3

你可以導入異常對象,並修改except塊:

import socket 

try: 
    soup = BeautifulSoup(urllib2.urlopen(url,timeout=10)) 

except urllib2.URLError as e: 
    print ("There was an error: %r" % e) 
except socket.timeout as e: # <-------- this block here 
    print "We timed out" 

更新:嗯,學到新的東西 - 只發現一個.reason屬性的引用:

except urllib2.URLError as e: 
    if isinstance(e.reason, socket.timeout): 
     pass # ignore this one 
    else: 
     # do stuff re other errors if you can... 
     raise # otherwise propagate the error