如何在Python请求中使用cookie?

问题描述 投票:0回答:4

我正在尝试登录某个页面并访问该页面中的另一个链接。

我从这次尝试中收到“405 Not allowed”错误:

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

我使用 Chrome 开发者工具检查了 post 方法详细信息,发现了一个似乎是 API 端点的 URL。我将有效负载发布到该 URL,它似乎有效;我得到的回复与我在开发人员中看到的类似。

不幸的是,当登录后尝试“获取”另一个 URL 时,我仍然从登录页面获取内容。 为什么登录不粘?我应该使用cookies吗?怎么办?

python cookies python-requests
4个回答
168
投票

您可以使用会话对象。它存储 cookie,以便您可以发出请求,并为您处理 cookie

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

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

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

您还可以将 cookie 数据保存到外部文件,然后重新加载它们以保持会话持久性,而无需每次运行脚本时都登录:

如何将请求(python)cookie保存到文件中?


99
投票

来自文档

  1. 从响应中获取cookie

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

    {'example_cookie_name': 'example_cookie_value'}

  2. 在后续请求时将 cookie 返回给服务器

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

19
投票

总结(@Freek Wiekmeijer,@gtalarico)其他人的回答:

登录逻辑

  • 很多资源(页面、api)需要
    authentication
    才可以访问,否则
    405 Not Allowed
  • 常见的
    authentication
    =
    grant access
    方法有:
    • cookie
    • auth header
      • Basic xxx
      • Authorization xxx

如何使用
cookie
中的
requests
进行身份验证

  1. 首先获取/生成cookie
  2. 为以下请求发送 cookie
  • 手动设置
    cookie
    headers
  • 自动处理
    cookie
    by
    requests
    's
    • session
      自动管理cookies
    • response.cookies
      手动设置cookie

使用
requests
session
自动管理cookie

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)

手动控制
requests
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)

6
投票

正如其他人指出的,这是如何将 cookie 作为字符串变量添加到 headers 参数的示例 -

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)
© www.soinside.com 2019 - 2024. All rights reserved.