Paul
Paul

Reputation: 177

How to use cookies with Python requests module?

I am trying to do a get request and saving the cookies from that and using it for a post request. I tried that with this code:

s = requests.Session()
resp = s.get(url1)
resp2 = requests.post(url2, data=payload, headers=headers, cookies=s.cookies)

but I can't get this to work correctly. The post request won't have the same cookies as the get request.

Am I doing something wrong?

Upvotes: 0

Views: 209

Answers (1)

Marco Bonelli
Marco Bonelli

Reputation: 69336

You are already using Session(), its whole purpose is to save you the hassle of handling cookies. It already stores the cookies obtained from the server and automatically sends/updates them in subsequent requests.

Here's how you should do it:

s = requests.Session()
resp = s.get(url1)
resp2 = s.post(url2, data=payload, headers=headers)

Upvotes: 1

Related Questions