【问题标题】:How to set and retrieve cookie in HTTP header in Python?如何在 Python 的 HTTP 标头中设置和检索 cookie?
【发布时间】:2011-08-02 03:23:51
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: python cookies http-headers


    【解决方案1】:

    您应该将 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 标头)。

    【讨论】:

    【解决方案2】:

    查看 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

    【讨论】:

    • 我没有明白“发送带有请求的 Set-Cookie 标头”的意思。你能给我举个例子吗???
    • 我不确定 Python 2,但在 3 上,您可以将最后一行缩短为 d.info()['Set-Cookie']
    • 哎呀,对不起。您实际上可以只使用d.getheader('Set-Cookie')(在 3.4.1 中测试)。
    • 当您获得带有 200 OK 响应的“Set-cookie”标头时,它可以工作。但是,如果您在 302“Found”响应中获得“Set-cookie”标头并且 Python 遵循重定向(默认情况下),则 d.getheader(...) 仅包含来自上次重定向的标头,并且没有“Set-cookie”标头.
    【解决方案3】:

    你可以在 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)
    

    【讨论】:

      【解决方案4】:

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

      导入请求 s = requests.Session() s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') r = s.get('http://httpbin.org/cookies') 打印(r.text) # '{"cookies": {"sessioncookie": "123456789"}}' 打印(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

      【讨论】:

        猜你喜欢
        • 2011-06-24
        • 2014-12-03
        • 2014-11-16
        • 2011-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多