進行異常處理我們經常使用try....except語句,在try中執行主要代碼,在except中捕獲異常信息,並進行相應的異常處理。
一、爬蟲中異常主要有兩大類:
(1)URLError類
(2)HTTPError類
def error_process():
try:
import urllib.request
import urllib.error
urllib.request.urlopen("http://blog.csdn.net")
print ("OK")
except urllib.error.URLError as e:
print (e.code) #異常狀態
print (e.reason) #異常原因
一般產生Error的原因有如下幾種可能:
- 鏈接不上服務器
- 遠程URL不存在
- 無網絡
- 觸發了HTTPError
注意:HTTPError無法處理以上前三種錯誤,要用URLError!
比如我們現在構造一個不存在的網址,引發遠程URL不存在的異常,此時不能通過HTTPError處理,要用URLError
def error_process():
try:
import urllib.request
import urllib.error
urllib.request.urlopen("http://blog.baiducsdn.net")
print ("OK")
except urllib.error.URLError as e:
#用HTTPError會報錯的
#print (e.code)
print (e.reason)
if __name__ =='__main__':
error_process()
輸出異常原因:
但素!!!在實際處理異常過程中,我們並不知道HTTPError是不是能處理,我們可以先讓其用HTTPError子類進行處理,若無法處理,再讓其用URLError進行處理,代碼如下:
def error_process():
try:
import urllib.request
import urllib.error
urllib.request.urlopen("http://blog.baiducsdn.net")
print ("OK")
except urllib.error.HTTPError as e:
print (e.code)
print (e.reaoson)
except urllib.error.URLError as e:
print (e.reason)
if __name__ =='__main__':
error_process()
在上述代碼中,我們先用子類進行異常處理,若無法處理,再用父類進行異常處理,此時,不管發生的是哪種異常,都能夠進行完美處理。
def error_process():
try:
import urllib.request
import urllib.error
urllib.request.urlopen("http://www.baiducsdn.net")
print ("OK")
except urllib.error.URLError as e:
print (e.code)
print (e.reason)
if __name__ =='__main__':
error_process()
e.code會報錯,因爲e.code這時候不存在
處理方法:可以用hasattr()函數來判斷是非具有這些屬性,這樣就不會出錯,也就是,有e.code 就輸出,沒有就自動忽略;e.reason同理。
修改後代碼:
def error_process():
try:
import urllib.request
import urllib.error
urllib.request.urlopen("http://www.baiducsdn.net")
print ("OK")
except urllib.error.URLError as e:
if hasattr(e,"code"):
print (e.code)
if hasattr(e, "reason"):
print (e.reason)
if __name__ =='__main__':
error_process()
運行結果:
二、常見的狀態碼及含義
200 OK 一切正常
301 Moved Permanently 重定向到心的URL,永久性
303 Found 重新定向到新的URL,非永久性(臨時的)
304 Not Modified 請求的資源未更新
400 Bad Request 非法請求
總結:
(1)如果是引發了HTTPError異常,則判斷出有e.code ,就會既輸出狀態碼也輸出錯誤原因
(2)若引發異常的原因是“連接不上服務器”、“遠程URL不存在”、“無網絡”等異常中的一個,則判斷沒有e.code。所以只會輸出e.rason .不管是何種原因。都能得到解決。
(3)學會使用try....except語句進行異常處理,在try 中執行主要代碼,在except中捕獲異常信息,並進行相應的處理。