简体   繁体   中英

How to transfer cookies to the page that I would like to download html?

Executes the code:

response = requests.get("https://google.com")
print(response.cookies)
cookies_dict = {"my_cookie": "cookie_value"}
response = requests.get("https://google.com", cookies=cookies_dict)
print(response.cookies)

I get a reply:

<RequestsCookieJar[]>
<RequestsCookieJar[]>

I use libraries:

from urllib.request import Request

I would like to transfer the cookie data to the website so that it can download the HTML content from the website with the use of this cookie. Unfortunately, when you try to send cookies, they are not added. I have already tried many ways. Unsuccessfully.

Could someone help me how to send cookies? How to otherwise download the html content of a page with assigned cookies?

The website I use in the project uses cookies for authorization. Without sending the cookie, I will not be able to download the content of the website.

//edit I changed the page example because it did not work like my project needed page.

If you print response.text, you can see the cookies

import requests

response = requests.get("http://httpbin.org/cookies")
print(response.text)
cookies_dict = {"my_cookie": "cookie_value"}
response = requests.get("http://httpbin.org/cookies", cookies=cookies_dict)
print(response.text)

Output

{
  "cookies": {}
}

{
  "cookies": {
    "my_cookie": "cookie_value"
  }
}

Or you can access the cookies directly by using response.json()['cookies']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM