如何在 Python 的 HTTP 标头中设置和检索 cookie?

2022-01-17 00:00:00 python http-headers cookies

问题描述

我需要从服务器发送的 HTTP 响应中获取 cookie,并将其放入下一个请求的标头中.我该怎么做?

I need to get the cookies from a HTTP response sent by a server and put it in the next request's header. How can I do it?

提前致谢.


解决方案

你应该使用 cookielib 模块 与 urllib.

You should use the cookielib module with urllib.

它将在请求之间存储 cookie,您可以在磁盘上加载/保存它们.这是一个例子:

It will store cookies between requests, and you can load/save them on disk. Here is an example:

import cookielib
import urllib2

cookies = cookielib.LWPCookieJar()
handlers = [
    urllib2.HTTPHandler(),
    urllib2.HTTPSHandler(),
    urllib2.HTTPCookieProcessor(cookies)
    ]
opener = urllib2.build_opener(*handlers)

def fetch(uri):
    req = urllib2.Request(uri)
    return opener.open(req)

def dump():
    for cookie in cookies:
        print cookie.name, cookie.value

uri = 'http://www.google.com/'
res = fetch(uri)
dump()

res = fetch(uri)
dump()

# save cookies to disk. you can load them with cookies.load() as well.
cookies.save('mycookies.txt')

请注意,NIDPREF 的值在请求之间是相同的.如果您省略了 HTTPCookieProcessor,这些将有所不同(urllib2 不会在第二次请求中发送 Cookie 标头).

Notice that the values for NID and PREF are the same between requests. If you omitted the HTTPCookieProcessor these would be different (urllib2 wouldn't send Cookie headers on the 2nd request).

相关文章