【问题标题】:Python - Using same cookie with different requestPython - 对不同的请求使用相同的 cookie
【发布时间】:2022-02-09 22:17:51
【问题描述】:

我需要使用相同的 cookie 发出三个请求。如果我使用此命令发出第一个请求:

s = requests.Session()
r1 = s.post("https://example.com/first.php", headers=headers1)
print(r1.cookies)
r2 = s.post("https://example.com/second.php", headers=headers1)
print(r2.cookies)

我得到这个输出:

<RequestsCookieJar[<Cookie PHPSESSID=3ht1qgfl4ot4lnrfemspkkk2ts for example.com/>]>
<RequestsCookieJar[]>

似乎在第二个请求中没有使用相同的 cookie。我也尝试过另一种方法:

r1 = requests.post("https://example.com/first.php", headers=headers1)
print(r1.cookies)
r2 = requests.post("https://example.com/second.php", headers=headers1, cookies=r1.cookies)
print(r2.cookies)

我得到这个输出 - 同样的问题:

<RequestsCookieJar[<Cookie PHPSESSID=mje0prfv97un49tkq381turq2d for example.com/>]>
<RequestsCookieJar[]>

谁能帮帮我,如何在第二个请求中使用相同的 cookie?

【问题讨论】:

    标签: python python-requests session-cookies


    【解决方案1】:

    它写在请求文档中,关于不会在第二个请求中发送 cookie

    https://docs.python-requests.org/en/master/user/advanced/#:~:text=This%20example%20will%20only%20send%20the%20cookies%20with%20the%20first%20request,%20but%20not%20the%20second

    我认为你可以尝试存储 cookie 并加载它

    import requests
    
    s = requests.Session()
    r1 = s.post("https://example.com/first.php", headers=headers1)
    print(r1.cookies)
    cookies = requests.utils.dict_from_cookiejar(r1.cookies)
    s.cookies.update(cookies)
    r2 = s.post("https://example.com/second.php", headers=headers1)
    print(r2.cookies)
    r3 = s.post("https://example.com/third.php", headers=headers1)
    print(r3.cookies)
    

    您可以在这里查看更多信息https://docs.python-requests.org/en/master/api/#api-cookies

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2021-12-20
      • 2019-05-07
      • 2021-11-25
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多