爬蟲2
阿新 • • 發佈:2018-03-27
color 產生 如果 rect onerror 說明 遠程 con 分享
爬取網頁的通用代碼框架
異常 | 說明 |
requests.ConnectionError | 網絡連接錯誤異常,比如DNS查詢失敗、拒絕連接等 |
requests.HTTPError | HTTP錯誤異常 |
requests.URLRequired | URL缺失異常 |
requests.TooManyRedirects | 超過最大重定向次數,產生重定向異常 |
requests.ConnectTimeout | 連接遠程服務器超時異常 |
requests.Timesout | 請求URL超時,產生超時異常 |
理解requests庫的異常:
r.raise_for_status() | 如果不是200,產生異常requests.HTTPError |
示例:
import requests def getHTMLText(url): try: r=requests.get(url,timeout=30) r.raise_for_status()#如果狀態不是200,引發HTTPError異常 r.encoding=r.apparent_encoding return r.text except: return ‘產生異常‘
結果:
爬蟲2