python请求获取cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25091976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python requests get cookies
提问by Danfi
x = requests.post(url, data=data)
print x.cookies
I used the requests library to get some cookies from a website, but I can only get the cookies from the Response, how to get the cookies from the Request? Thanks!
我使用请求库从网站获取一些cookie,但我只能从响应中获取cookie,如何从请求中获取cookie?谢谢!
采纳答案by alecxe
Alternatively, you can use requests.Sessionand observe cookiesbefore and after a request:
或者,您可以在请求前后使用requests.Session和观察cookies:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
回答by Or Duan
If you need the pathand thedomainfor each cookie, which get_dict()is not exposes, you can parse the cookies manually, for instance:
如果您需要每个未公开的cookie的path和,您可以手动解析 cookie,例如:domainget_dict()
[
{'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
for c in session.cookies
]

