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

前端 未结 4 1844
孤独总比滥情好
孤独总比滥情好 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:13

    Current answer is to use Requests module and the requests.Session object.

    • Quick Start; http://docs.python-requests.org/en/master/user/quickstart/#json-response-content
    • Sessions: http://docs.python-requests.org/en/master/user/advanced/#session-objects
        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)]
    

    You may need to pip install requests or pipenv install requests first.

提交回复
热议问题