Key takeaways:
- Sessions automatically track your data across multiple requests.
- You can convert cookie jars into standard Python dictionaries to inspect them easily.
- To keep cookies between script runs, save them to a file with a cookie jar such as MozillaCookieJar.
When writing scripts for web scraping or automation, you will often need the server to remember you across different page loads.
Websites handle this using cookies. The server sends these small pieces of data in HTTP headers. With requests.Session(), your Python script stores them in memory and sends them back with future requests so the server knows it is still you.
How do cookies work in Python requests?
The process starts when a server sends a Set-Cookie header to your script. That cookie usually holds a session ID that links you to your login on the server, or a preference such as language or currency. If you’re using a Session object, the requests library automatically saves this data and includes it in a Cookie header on your next request.
You can test this by hitting endpoints like https://httpbin.org/cookies, which will show you what cookie data your script sent over the network.
The response object has a cookies attribute, a RequestsCookieJar, which makes it easy to read the returned cookies without manually parsing the raw HTTP response.
While cookies are passed via HTTP headers, they differ from standard headers or bearer tokens. The server sets them, and a cookie jar stores them and sends them back only to the domain and path they belong to. A bearer token goes in an Authorization header that you add to each request yourself.
How to get cookies from a response
Once you make a request, you can access the returned cookies through the response object and its cookies attribute. Since the default cookie jar contains extra metadata, you will usually want to convert it to a standard Python dictionary using the get_dict() method.
It leaves you with simple key-value pairs, which makes the cookie values much easier to print or use elsewhere in your script, though you do lose the specific domain and path details.
Here’s an example that asks httpbin to set two cookies and reads them from the response:
import requests
response = requests.get(
"https://httpbin.org/cookies/set?session_id=abc123&theme=dark",
allow_redirects=False,
)
print(response.cookies)
print(response.cookies.get_dict())
print(response.cookies["theme"])
The first line prints the whole cookie jar, the second prints {'session_id': 'abc123', 'theme': 'dark'}, and the third prints dark.
The allow_redirects=False argument matters here. httpbin sets these cookies on a redirect, and response.cookies only holds the cookies from the final response, so without it the jar would come back empty.
How to send cookies with a GET request
To send cookies right away, pass a dictionary to the cookies parameter in your GET request. The library automatically formats this into the correct HTTP Cookie header for you, as this request to httpbin shows:
import requests
cookies = {"session_id": "abc123", "theme": "dark"}
response = requests.get("https://httpbin.org/cookies", cookies=cookies)
print(response.json())
httpbin echoes back {'cookies': {'session_id': 'abc123', 'theme': 'dark'}}, which confirms that both cookies arrived in the Cookie header.
If you already have a populated cookie jar from an earlier request, you can pass that to the cookies parameter to keep your session state intact.
How to set cookies in a POST request
When making a POST request, your form data or JSON goes into the request body, but you can still pass a dictionary to the cookies parameter to keep your session active, as in this example:
import requests
response = requests.post(
"https://httpbin.org/post",
data={"query": "laptops"},
cookies={"session_id": "abc123"},
)
data = response.json()
print(data["form"])
print(data["headers"]["Cookie"])
httpbin returns {'query': 'laptops'} as the form data and session_id=abc123 as the Cookie header, so the two travel separately.
The server reads the body to process your data while using the cookie values to verify who you are. Keep in mind that if you use a Session object, the library attaches the cookies the server has set automatically, so you will not need this parameter for them. Cookies you pass with the cookies parameter apply to that one request only, even in a session.
How to save and load cookies in Python requests
Using requests.Session()
If you are making several requests to the same website during web scraping, use a Session object. The session is like a browser tab. It holds onto the cookie data it gets from the first response and automatically attaches it to your future requests.
In this example, the first request sets a cookie, and the second sends it back without any extra code:
import requests
with requests.Session() as session:
session.get("https://httpbin.org/cookies/set?session_id=abc123")
response = session.get("https://httpbin.org/cookies")
print(response.json())
print(session.cookies.get_dict())
Both lines show session_id set to abc123: the first comes from httpbin’s echo, and the second from the session’s own cookie jar. The with block closes the session when you’re done.
For longer scraping jobs, set a timeout on each request too, so one slow server can’t stall the whole session.
Saving cookies to a file
Since a standard session only stores cookies in memory, you will lose them when your web scraping script finishes. To save your session state for later, you can attach a MozillaCookieJar to your session. It captures the incoming cookies, and calling its save() method writes them to a local text file:
import requests
from http.cookiejar import MozillaCookieJar
session = requests.Session()
session.cookies = MozillaCookieJar("cookies.txt")
session.get("https://httpbin.org/cookies/set?session_id=abc123")
session.cookies.save(ignore_discard=True)
The ignore_discard=True argument is what keeps your login. Session cookies, the kind many sites use for logins, have no expiry date, and save() skips them by default, so without it the file can end up without the cookie you need.
Loading cookies in a new session
The next time you run your script, you can tell your new session to read that saved text file and load the cookies. As long as the server hasn’t ended that session, you can resume it without having to go through authentication again:
import requests
from http.cookiejar import MozillaCookieJar
session = requests.Session()
session.cookies = MozillaCookieJar("cookies.txt")
session.cookies.load(ignore_discard=True)
response = session.get("https://httpbin.org/cookies")
print(response.json())
Pass ignore_discard=True to load() as well. Otherwise the session cookie you saved is skipped again, and the server treats you as logged out.
Common Python requests cookie issues and solutions
- Missing or expired cookie values will usually cause the server to reject your request or log you out. The cookie jar drops expired cookies on its own, so watch for a 401 or a redirect to the login page and log in again.
- Servers use domain, path, and secure flags to restrict cookie values. If your request URL does not meet these rules, your script will not send the cookie back. For example, a cookie set for /cart isn’t sent to /account, and a Secure cookie never goes over plain http://.
- Cookies will not persist between requests if you use basic methods like requests.get() instead of a Session object. Cookies passed with the cookies parameter don’t persist either, so add lasting ones with session.cookies.set() and the site’s domain.
- Rotating proxies can break your session because some servers invalidate a session when its cookie suddenly arrives from a different IP address. Use a sticky session, which keeps the same IP, for anything that needs a login.
- Saved cookies work like passwords, since anyone who has your session cookie can skip authentication and act as you on that site. Keep cookie files out of version control and shared folders, and don’t hard-code session cookies in your scripts.
Keep Python Requests Sessions Logged In on One IP
Get ISP proxiesConclusion
Cookies are how a server remembers your script from one request to the next. For a single call, pass them to the cookies parameter. For anything longer, such as logging in and then loading several pages, use requests.Session() so the library stores and resends cookies for you.
To keep that state between script runs, save the jar with MozillaCookieJar and ignore_discard=True, and guard the file like a password. If you send the session through rotating proxies, use a sticky IP so the server sees one visitor throughout. That covers most cookie problems in web scraping and automation.
FAQ
Does Python requests automatically save cookies?
If you use a Session object, the library automatically saves cookies and sends them with every later request to the domain and path they belong to. If you use basic functions like requests.get(), the cookies are not saved for the next request.
How do you persist cookies between Python scripts?
You can use a class like MozillaCookieJar to save your cookies to a local text file. Pass ignore_discard=True to both save() and load(), or session cookies are left out. Your next script can then load that file to pick up right where the first one left off.
Why are session cookies not working in Python requests?
The most common reason is forgetting to use a Session object. Alternatively, the server might have set strict domain or path rules that your next request does not meet.
Can you use Python requests cookies with proxies?
Yes, you can pass proxies to your session. Just keep in mind that changing your IP address frequently might cause the target server to invalidate your session for security reasons.