cookies in python requests

Cookies in Python Requests

When making HTTP requests in Python using the requests library, cookies can be used to maintain state across multiple requests. Cookies are small pieces of data that are sent by a website and stored on the client side, which can be used to remember user preferences, login status, and other information.

To send a cookie with a request, the cookies parameter can be included in the request:

import requests

url = 'https://example.com'
cookies = {'session_id': '1234'}

response = requests.get(url, cookies=cookies)

In this example, a GET request is sent to 'https://example.com' with a cookie containing a session_id value of '1234'. The cookies parameter is a dictionary that maps cookie names to values.

Retrieving Cookies from a Response

When a response is received from a server, cookies can be retrieved from the response object:

response = requests.get(url)

cookies = response.cookies
session_id = cookies['session_id']

In this example, the cookies attribute of the response object is a RequestsCookieJar object that behaves like a dictionary. The session_id cookie value is retrieved using dictionary-like syntax.

Persisting Cookies Across Requests

To persist cookies across multiple requests, a session object can be used:

session = requests.Session()

# Send first request and store cookies
response1 = session.get(url)

# Send second request with cookies from first request
response2 = session.get(url)

In this example, a session object is created and used to send two requests to the same URL. The cookies from the first request are automatically stored and sent with the second request.