Requests - Working with Cookies


Advertisements

This chapter will discuss how to deal with cookies. You can get the cookies as well as send your cookies while calling the URL using the requests library.

The url, https://jsonplaceholder.typicode.com/users when hits in the browser we can get the details of the cookies as shown below −

Typicode Sourcecode

You can read the cookies as shown below −

Example

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.cookies["__cfduid"])

Output

E:\prequests>python makeRequest.py
d1733467caa1e3431fb7f768fa79ed3741575094848

You can also send cookies when we make a request.

Example

import requests
cookies = dict(test='test123')
getdata = requests.get('https://httpbin.org/cookies',cookies=cookies)
print(getdata.text)

Output

E:\prequests>python makeRequest.py
{
   "cookies": {
      "test": "test123"
   }
}
Advertisements