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

How to set and retrieve cookie in HTTP header in Python?(如何在 Python 的 HTTP 标头中设置和检索 cookie?)

本文介绍了如何在 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')

请注意,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).

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

本文标题为:如何在 Python 的 HTTP 标头中设置和检索 cookie?

基础教程推荐