无法从网站 Python 获取 cookie

时间:2020-12-30 13:12:34

标签: python python-requests

我无法从以下代码中获取 cookie。

我尝试了不同的刮板,但没有任何进展。

有没有人知道如何实现它?

import requests
session = requests.Session()
print(session.cookies.get_dict())
response = session.get('https://example.com')
print(session.cookies.get_dict())

任何方法的任何建议都值得赞赏。

谢谢

1 个答案:

答案 0 :(得分:2)

如果请求看起来不是来自浏览器,则某些站点(显然包括这个站点)不会返回任何 cookie。

您需要传递一些标头以使其看起来像是来自浏览器的请求——User-agent 通常足以让您开始使用。

举个例子,考虑一下:

import requests

session = requests.Session()
print(session.cookies.get_dict())

# Impersonate Firefox
headers = {
    'User-agent': 'Mozilla/5.0'
}

response = session.get('https://nseindia.com', headers=headers)
print(session.cookies.get_dict())
# Should now give you the cookies

this 帖子中有更多关于设置 User-agent 的讨论。