如何在 Python 请求中使用 cookie

我试图登录到一个网页,并访问该网页中的另一个链接。

payload={'username'=<username>,'password'=<password>}
with session() as s:
r = c.post(<URL>, data=payload)
print r
print r.content

这给了我一个“405不允许”的错误。 我使用 chrome 开发工具检查了 post 方法的细节,可以看到一个 api (URL/api/auth)。 我发布了一个有效负载的网址,它正在工作,我得到了一个类似的回应,我可以看到在开发人员。

不幸的是,当尝试’得到’另一个网址登录后,我仍然从登录页面的内容。 为什么登录不粘贴? 我应该使用 cookie 吗? 我是个新手,所以我真的不知道怎么用饼干。

296438 次浏览

From the documentation:

  1. get cookie from response

     url = 'http://example.com/some/cookie/setting/url'
    r = requests.get(url)
    r.cookies
    

    {'example_cookie_name': 'example_cookie_value'}

  2. give cookie back to server on subsequent request

     url = 'http://httpbin.org/cookies'
    cookies = {'cookies_are': 'working'}
    r = requests.get(url, cookies=cookies)`
    

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session()
# all cookies received will be stored in the session object


s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

Summary (@Freek Wiekmeijer, @gtalarico) other's answer:

Logic of Login

  • Many resource(pages, api) need authentication, then can access, otherwise 405 Not Allowed
  • Common authentication=grant access method are:
    • cookie
      • Basic xxx
      • Authorization xxx

How use cookie in requests to auth

  1. first get/generate cookie
  2. send cookie for following request
  • manual set cookie in headers
  • auto process cookie by requests's
    • session to auto manage cookies
    • response.cookies to manually set cookies

use requests's session auto manage cookies

curSession = requests.Session()
# all cookies received will be stored in the session object


payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth


# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)


curSession.get(thirdUrl)

manually control requests's response.cookies

payload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)


# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)


resp3 = requests.get(thirdUrl, cookies= resp2.cookies)

As others noted, Here is an example of how to add cookies as string variable to the headers parameter -

    headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...',
'cookie': '_fbp=fb.1.1654447470850.2143140577; _ga=GA1.2.1...'
}
response = requests.get(url, headers=headers)