Remove cookies from Python requests

I created a variable: s = requests.session()

how to clear all cookies in this variable?

+9
python cookies session python-requests
source share
2 answers

The Session.cookies object implements a full mutable matching interface , so you can call:

 s.cookies.clear() 

to clear all cookies.

Demo:

 >>> import requests >>> s = requests.session() >>> s.get('http://httpbin.org/cookies/set', params={'foo': 'bar'}) <Response [200]> >>> s.cookies.keys() ['foo'] >>> s.get('http://httpbin.org/cookies').json() {u'cookies': {u'foo': u'bar'}} >>> s.cookies.clear() >>> s.cookies.keys() [] >>> s.get('http://httpbin.org/cookies').json() {u'cookies': {}} 

However, the easiest way to create a new session is:

 s = requests.session() 
+28
source share

How can I delete all cookies stored in python? I try to send a request without cookies set, but Python each time it includes cookies stored on my computer in the request header, and then the webpage does not load properly.

  import requests headers = { 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'cs-CZ,cs;q=0.9' } s=requests.session() s.get('https://admin.booking.com/', headers=headers) r=s.get('https://admin.booking.com/', headers=headers) 

I tried to clear cookies with

 s.cookies.clear() r.cookies.clear() 
0
source share

All Articles