In Web development, Cookies are an important mechanism for saving user session information between the client and the server. Python's Requests library provides a powerful and simple method for processing HTTP requests, allowing us to easily read and set Cookies. This article will detail how to use the Requests library in Python to process Cookies.
Read Cookies
After sending an HTTP request, the server may return some cookies, which can be obtained through response.cookies
;
import requests
response = requests.get('http://google.com')
print(response.cookies)
response.cookies
returns a RequestsCookieJar
object instance;
Traverse all cookies:
for cookie in response.cookies:
print(f'{cookie.name}: {cookie.value}')
Get a cookie. If the cookie does not exist, a KeyError
will be raised:
print(response.cookies['AEC'])
print(response.cookies.get('AEC'))
Set Cookies
In simple scenarios, if you only need to pass some basic cookie information, you can directly use a dictionary to pass cookies;
import requests
url = "http://example.com"
cookies = {
'token': '123456'
}
response = requests.get(url, cookies=cookies)
In this example, the cookies
parameter receives a normal dictionary, the key is the name of the cookie, and the value is the value of the corresponding cookie; this method is very simple and suitable for handling basic Cookie scenarios, but cannot handle cookie-related attributes (such as domain, path, etc.).
RequestsCookieJar Object
In addition to storing basic cookie key-value pairs, RequestsCookieJar
can also store other attributes of cookies. For example, you can specify the domain, path, expiration time, etc. for each cookie, which is very important in complex Web request scenarios.
import requests
import time
jar = requests.cookies.RequestsCookieJar()
expires_time = int(time.time()) + 3600
jar.set('token', '123456', domain='example.com', path='/')
jar.set('token2', '123456', domain='example.com', path='/', expires=expires_time)
response = requests.get('https://example.com', cookies=jar)
Update RequestsCookieJar
If you need to share cookies between multiple requests (for example, in scenarios where you need to maintain user login status or other session information), it is recommended to use the Session object.
Update the cookies returned by the server:
import requests
jar = requests.cookies.RequestsCookieJar()
response = requests.post('https://example.com/login')
jar.update(response.cookies)
response = requests.get('https://example.com/do',cookies=jar)