You can do this by defining a cookie policy to reject all cookies:
from http import cookiejar # Python 2: import cookielib as cookiejar
class BlockAll(cookiejar.CookiePolicy):
return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False
netscape = True
rfc2965 = hide_cookie2 = False
(Note that http.cookiejar
's API requires you to define a bunch of attributes and methods, as shown.)
Then, set the cookie policy on your Requests session:
import requests
s = requests.Session()
s.cookies.set_policy(BlockAll())
It will now not store or send cookies:
s.get("https://httpbin.org/cookies/set?foo=bar")
assert not s.cookies
As an aside, if you look at the code, the convenience methods in the requests
package (as opposed to those on a requests.Session
object) construct a new Session
each time. Therefore, cookies aren't persisted between separate calls to requests.get
. However, if the first page sets cookies and then issues an HTTP redirect, the target page will see the cookies. (This is what happens with the HTTPBin /cookies/set
call, which redirects to /cookies
.)
So depending on what behavior you want for redirects, you might not need to do anything special. Compare:
>>> print(requests.get("https://httpbin.org/cookies/set?foo=bar").json())
{'cookies': {'foo': 'bar'}}
>>> print(requests.get("https://httpbin.org/cookies").json())
{'cookies': {}}
>>> s = requests.Session()
>>> print(s.get("https://httpbin.org/cookies/set?foo=bar").json())
{'cookies': {'foo': 'bar'}}
>>> print(s.get("https://httpbin.org/cookies").json())
{'cookies': {'foo': 'bar'}}
>>> s = requests.Session()
>>> s.cookies.set_policy(BlockAll())
>>> print(s.get("https://httpbin.org/cookies/set?foo=bar").json())
{'cookies': {}}
>>> print(requests.get("https://httpbin.org/cookies").json())
{'cookies': {}}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…