The Response object returned by requests contains the response header attribute headers:
import requests as r
response = r.get("http://example.com")
print(response.headers)
Accessing the response.headers
property will get a dictionary-like object;
This dictionary-like object is actually an instance of requests.structures.CaseInsensitiveDict
;
Its characteristic is that the dictionary keys are case-insensitive.
You can access response.headers
like a dictionary. Since HTTP headers are case-insensitive, we can use any case format as the key to access this dictionary:
The following methods have the same effect:
response.headers['content-type']
response.headers['CONTENT-type']
response.headers.get('content-type')
response.headers.get('Content-type')
Traverse all Headers information
import requests as r
response = r.get("http://example.com")
for key,value in response.headers.items():
print(f'{key}: {value}')
Operation effect
Connection: close Content-Length: 648 Accept-Ranges: bytes Age: 369357 Cache-Control: max-age=604800 Content-Encoding: gzip Content-Type: text/html; charset=UTF-8 Date: Mon, 30 Sep 2024 12:09:48 GMT Etag: "3147526947+gzip" Expires: Mon, 07 Oct 2024 12:09:48 GMT Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT Server: ECAcc (chd/072B) Vary: Accept-Encoding X-Cache: HIT