all Python 3urllib.requestterm
urllib.request.HTTPCookieProcessor
cookies and proxies
Connects an opener to an http.cookiejar.CookieJar: it accepts cookies from responses and sends them with later requests.
Syntax
urllib.request.HTTPCookieProcessor(cookiejar=None)
Without it urllib keeps no cookies at all: Set-Cookie in a response is thrown away, so a login is not remembered between requests. It works only for the opener it was added to — urlopen() without install_opener() sees no cookies. To keep them between runs, pass a MozillaCookieJar with a file name and call save().
Examples
import email.message, io, urllib.error, urllib.request, urllib.response
def reply(req, code, body=b'', **headers):
msg = email.message.Message()
for name, value in headers.items():
msg[name.replace('_', '-')] = value
resp = urllib.response.addinfourl(io.BytesIO(body), msg, req.full_url, code)
resp.msg = 'demo'
return resp
import http.cookiejar
class Server(urllib.request.BaseHandler):
handler_order = 100
def http_open(self, req):
print(req.selector, req.get_header('Cookie'))
if req.selector == '/login':
return reply(req, 200, Set_Cookie='sid=42; Path=/')
return reply(req, 200)
jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(Server, urllib.request.HTTPCookieProcessor(jar))
opener.open('http://example.com/login')
opener.open('http://example.com/home')
# → /login None / /home sid=42
See also
Open in the full glossarydocs.python.orgReport an inaccuracy