Search code examples
pythonformscookiespython-requests

Cookies Python Requests [don't get cookies]


It's the Python code to use this site: 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)

I just wanna get cookies, but i can't what I must change?

So to fix the problem I tried use headers and its full need headers (you can check, but some data maybe change)

But print(s.cookies) also returns <RequestsCookieJar[]>

I don't know how to fix but I can say that payload isn't Request Payload it's Form Data


Solution

  • Your code sends data in JSON format while the site looks for normal form data.

    You should modify your s.post to use data= instead of json= to change the format from application/json to application/x-www-form-urlencoded.

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

    Now, it prints:

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

    Also, you don't need to manually set headers for this to work. requests will set those automatically.