我有這個代碼,在第二個鏈接中它應該引發例外 404。
問題是我確實按照我編碼的方式獲取了訊息,但我也收到了回溯訊息,就像我的代碼有問題一樣。
它是一個名為“get_headers_if”的函式,輸入是 response_url 或 response_url_2。

import requests
import json
def get_headers_if(response):
if response.status_code==200:
headers=response.headers
print("The headers for this URL:", response.url, "are: ",headers)
else:
raise Exception("Unexpected response (%s: %s)." % (response.status_code, response.reason))
response_url=requests.get("http://wikipedia.org")
response_url_2=requests.get("http://google.com/thehearthisflat")
get_headers_if(response_url)
get_headers_if(response_url_2)
uj5u.com熱心網友回復:
您可以提升狀態并進行例外處理。默認情況下,請求庫提供檢查狀態代碼和引發例外的選項。您可以在例外列印陳述句中修改例外列印的內容。
import requests
def get_headers_if(response):
try:
response.raise_for_status()
headers=response.headers
print("The headers for this URL:", response.url, "are: ",headers)
except requests.exceptions.HTTPError as err:
print("Unexpected response (%s)." % err)
response_url=requests.get("http://wikipedia.org")
response_url_2=requests.get("http://google.com/thehearthisflat")
get_headers_if(response_url)
get_headers_if(response_url_2)
更多詳情:https : //github.com/psf/requests/blob/b0e025ade7ed30ed53ab61f542779af7e024932e/requests/models.py#L937
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363745.html
