如何在Python的HTTP头中设置和检索cookie? [英] How to set and retrieve cookie in HTTP header in Python?

查看:490
本文介绍了如何在Python的HTTP头中设置和检索cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从服务器发送的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')

请注意 NID PREF 在请求之间相同。如果你省略 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).

这篇关于如何在Python的HTTP头中设置和检索cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆