代码之家  ›  专栏  ›  技术社区  ›  Морфей

Cookies Python请求〔不要获取Cookies〕

  •  1
  • Морфей  · 技术社区  · 3 年前

    这是使用此网站的Python代码: https://setcookie.net/ :

    import requests
    s = requests.Session()
    
    headers = {
      'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
      'Accept-Encoding':'gzip, deflate, br',
      'Accept-Language':'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
      'Cache-Control':'max-age=0',
      'Content-Length':'58',
      'Content-Type':'application/x-www-form-urlencoded',
      'Cookie':'__SecureToken=1234',
      'Origin':'https://setcookie.net',
      'Referer':'https://setcookie.net/',
      'Sec-Ch-Ua':'"Not/A)Brand";v="99", "Google Chrome";v="115", "Chromium";v="115"',
      'Sec-Ch-Ua-Mobile':'?0',
      'Sec-Ch-Ua-Platform':'"Windows"',
      'Sec-Fetch-Dest':'document',
      'Sec-Fetch-Mode':'navigate',
      'Sec-Fetch-Site':'same-origin',
      'Sec-Fetch-User':'?1',
      'Upgrade-Insecure-Requests':'1',
      'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
    }
    
    payload = {
      'name':'__Secure-next-auth.session-token.0',
      'value':'please',
      'path':'/',
      'dom':'none',
      'ss':'notset',
      'httponly':'on'
    }
    
    r = s.post('https://setcookie.net/',json=payload,headers=headers)
    
    print(s.cookies)
    

    我只想得到饼干,但我不能,我必须改变什么?

    所以为了解决这个问题,我试着用 headers 以及它的全部需求标头(您可以检查,但有些数据可能会更改)

    但是 print(s.cookies) 也返回 <RequestsCookieJar[]>

    我不知道怎么解决,但我可以这么说 payload 不是 Request Payload 它是 Form Data

    1 回复  |  直到 3 年前
        1
  •  1
  •   miloserdow    3 年前

    您的代码以JSON格式发送数据,而网站则查找正常形式的数据。

    您应该修改 s.post 使用 data= 而不是 json= 更改格式 application/json 到 application/x-www-form-urlencoded 。

    r = s.post('https://setcookie.net/', data=payload, headers=headers)
    

    现在,它打印:

    <RequestsCookieJar(<Cookie help=please for setcookie.net/>]>
    

    此外,您不需要手动设置标头即可实现此操作。 requests 将自动设置。