In the Python requests library, you can use requests.cookies.RequestsCookieJar to manage cookies. There are two primary methods to add cookies to the CookieJar, and I will explain each method in detail with examples.
Method 1: Directly Using the set Method
The RequestsCookieJar class provides a set method that allows you to directly set the cookie name, value, and optional parameters such as domain and path.
pythonimport requests # Create a new session object session = requests.Session() # Retrieve the session's cookiejar cookie_jar = session.cookies # Add a cookie to the cookiejar cookie_jar.set('cookie_name', 'cookie_value', domain='example.com', path='/') # Send a request response = session.get('https://example.com') # Print the response cookies print(response.cookies)
In this example, we first create a requests.Session object and then retrieve its cookiejar. Using the cookiejar.set method, we add a cookie named 'cookie_name' with the value 'cookie_value' and specify the domain and path. Subsequently, when we send a request to 'https://example.com', this cookie will be automatically included in the request.
Method 2: Direct Assignment via Dictionary
Another method to add cookies is to directly assign values to the cookiejar using a dictionary. This method is straightforward but does not support setting additional cookie attributes such as domain or path.
pythonimport requests # Create a new session object session = requests.Session() # Add a cookie session.cookies['cookie_name'] = 'cookie_value' # Send a request response = session.get('https://example.com') # Print the response cookies print(response.cookies)
In this example, we directly add the cookie to the session.cookies dictionary using key-value pairs. This method is simple and direct, but if you need to set other cookie attributes (such as expiration, domain, or path), you should use the previous method.
Each method has its own use case, and you can choose the appropriate method based on your specific requirements.