Putting a `Cookie` in a `CookieJar`

前端 未结 10 1455
谎友^
谎友^ 2020-11-30 01:45

I\'m using the new Python Requests library to make http requests. I obtain a cookie from the server as text. How do I turn that into a CookieJar with the cookie

10条回答
  •  抹茶落季
    2020-11-30 02:36

    As dstanek answered, requests will automatically put response cookies in a cookie jar for you.
    However, if you manually specify a Cookie header entry, requests will not put those cookies in a jar for you. This means any subsequent requests will be lacking your initial set of cookies, but will have any new cookies going forward.

    If you do need to manually create a cookie jar for requests, use requests.cookies.RequestsCookieJar. In case their example code changes:

    jar = requests.cookies.RequestsCookieJar()
    jar.set('tasty_cookie', 'yum',   domain='httpbin.org', path='/cookies')
    jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
    url = 'http://httpbin.org/cookies'
    r = requests.get(url, cookies=jar)
    

    Note that if you provide a cookie jar and a Cookie header, the header takes precedence, but the cookie jar will still be maintained for future requests.

提交回复
热议问题