Python中Requests模組的異常值處理
在我們用Python的requests模組進行爬蟲時,一個簡單高效的模組就是requests模組,利用get()或者post()函式,傳送請求。
但是在真正的實際使用過程中,我們可能會遇到網路的各種變化,可能會導致請求過程發生各種未知的錯誤導致程式中斷,這就使我們的程式不能很好的去處理錯誤。所以為了使我們的程式在請求時遇到錯誤,可以捕獲這種錯誤,就要用到try…except方法,以及瞭解requests可能發生的各種錯誤.
以下是request.exceptions下的各種異常錯誤:
RequestException:
HTTPError(RequestException)
UnrewindableBodyError(RequestException)
RetryError(RequestException)
ConnectionError(RequestException) ProxyError(ConnectionError)
SSLError(ConnectionError)
ConnectTimeout(ConnectionError, Timeout)
Timeout(RequestException) ReadTimeout
URLRequired(RequestException)
TooManyRedirects(RequestException)
MissingSchema(RequestException, ValueError)
InvalidSchema(RequestException,ValueError)
InvalidURL(RequestException,ValueError)
InvalidHeader(RequestException,ValueError)
ChunkedEncodingError(RequestException)
StreamConsumedError(RequestException,TypeError)
ContentDecodingError(RequestException,BaseHTTPError)
在實際應用的過程中,我們可以把請求放在try下,把可能發生的異常用except獲取:
while True: #一直迴圈,知道訪問站點成功
try:
#以下except都是用來捕獲當requests請求出現異常時,
# 通過捕獲然後等待網路情況的變化,以此來保護程式的不間斷執行
req = requests.get(company_url, headers = headers, timeout = 20)
break
except requests.exceptions.ConnectionError:
print ('ConnectionError -- please wait 3 seconds')
time.sleep(3)
except requests.exceptions.ChunkedEncodingError:
print('ChunkedEncodingError -- please wait 3 seconds')
time.sleep(3)
except:
print('Unfortunitely -- An Unknow Error Happened, Please wait 3 seconds' )
time.sleep(3)