[英]urllib3 how to find code and message of Http error
我正在使用python捕獲HTTP錯誤,但我想知道該錯誤的代碼(例如400、403,..)。 另外,我想獲得錯誤消息。 但是,我在文檔中找不到這兩個屬性。 有人可以幫忙嗎? 謝謝。
try:
"""some code here"""
except urllib3.exceptions.HTTPError as error:
"""code based on error message and code"""
假設您是在說“錯誤消息”時指的是HTTP響應的描述,則可以使用來自http.client
responses
,如以下示例所示:
import urllib3
from http.client import responses
http = urllib3.PoolManager()
request = http.request('GET', 'http://google.com')
http_status = request.status
http_status_description = responses[http_status]
print(http_status)
print(http_status_description)
...執行時將為您提供:
200
OK
在我的例子中。
希望對您有所幫助。 問候。
以下示例代碼說明了響應的狀態代碼和錯誤原因:
import urllib3
try:
url ='http://httpbin.org/get'
http = urllib3.PoolManager()
response=http.request('GET', url)
print(response.status)
except urllib3.exceptions.HTTPError as e:
print('Request failed:', e.reason)
狀態碼來自響應,而HTTPError表示urllib3無法獲取響應。 狀態碼400+不會觸發urllib3的任何異常。
為什么要捕獲它作為例外? 您希望看到http響應,因此您無需將其作為例外處理。
您可以簡單地發出HTTP請求並讀取響應,如下所示:
import urllib3
http = urllib3.PoolManager()
req = http.request('GET', 'http://httpbin.org/robots.txt')
status_code = req.status
server_response = req.data
檢查urllib3 readthedocs以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.