How to set and retrieve cookie in HTTP header in Python?

前端 未结 4 1848
孤独总比滥情好
孤独总比滥情好 2020-12-07 23:34

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?

Thanks in advance.

4条回答
  •  余生分开走
    2020-12-08 00:06

    Look at urllib module:

    (with Python 3.1, in Python 2, use urllib2.urlopen instead) For retrieving cookies:

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

    And for sending, simply send a Cookie header with request. Like that:

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

    Edit:

    The "http.cookie"("Cookie" for Python 2) may work for you better:

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

提交回复
热议问题