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

时间:2011-04-09 16:00:12

标签: python cookies http-headers

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

提前致谢。

4 个答案:

答案 0 :(得分:25)

您应该将cookielib module与urllib一起使用。

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

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个标头。)

答案 1 :(得分:12)

看看urllib模块:

(使用Python 3.1,在Python 2中,使用urllib2.urlopen代替) 用于检索cookie:

>>> import urllib.request
>>> d = urllib.request.urlopen("http://www.google.co.uk")
>>> d.getheader('Set-Cookie')
'PREF=ID=a45c444aa509cd98:FF=0:TM=14.....'

对于发送,只需发送带有请求的Cookie标头。像那样:

r=urllib.request.Request("http://www.example.com/",headers={'Cookie':"session_id=1231245546"})
urllib.request.urlopen(r)

编辑:

“http.cookie”(Python 2的“Cookie”)可能对你有用:

http://docs.python.org/library/cookie.html

答案 2 :(得分:4)

您可以在Python 2.7中使用

url="http://google.com"
request = urllib2.Request(url)
sock=urllib2.urlopen(request)
cookies=sock.info()['Set-Cookie']
content=sock.read()
sock.close()
print (cookies, content)

并在发送请求时

def sendResponse(cookies): 
import urllib
request = urllib2.Request("http://google.com")
request.add_header("Cookie", cookies)
request.add_data(urllib.urlencode([('arg1','val1'),('arg1','val1')]))
opener=urllib2
opener=urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
sock=opener.open(request)
content=sock.read()
sock.close()
print len(content)

答案 3 :(得分:0)

目前的答案是使用Requests模块和requests.Session对象。

    import requests
    s = requests.Session()
    s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
    r = s.get('http://httpbin.org/cookies')
    print(r.text)
    # '{"cookies": {"sessioncookie": "123456789"}}'

    print(s.cookies)
    # RequestsCookieJar[Cookie(version=0, name='sessioncookie', value='123456789', port=None, port_specified=False, domain='httpbin.org', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]

您可能需要先pip install requestspipenv install requests