因此,我尝试使用requests
库编写一个小的脚本,该脚本向站点(例如github.com)发出请求,并解析响应标头中的cookie。因此,当您向github.com发出请求时,有3个不同的Set-Cookie
标头为:
Set-Cookie: has_recent_activity=1; path=/; expires=Thu, 27 Dec 2018 07:54:16 -0000
Set-Cookie: logged_in=no; domain=.github.com; path=/; expires=Mon, 27 Dec 2038 06:54:16 -0000; secure; HttpOnly
Set-Cookie: _gh_sess=MldFM3p...; path=/; secure; HttpOnly
现在,当您通过requests
API发出请求并通过Set-Cookie
检查req.headers.get('Set-Cookie')
标头时,所有这些cookie值都将汇总为一个:
has_recent_activity=1; path=/; expires=Thu, 27 Dec 2018 07:54:16 -0000, logged_in=no; domain=.github.com; path=/; expires=Mon, 27 Dec 2038 06:54:16 -0000; secure; HttpOnly, _gh_sess=MldFM3p...; path=/; secure; HttpOnly
所以我的问题是,如何获取服务器发送的 3个截然不同的完整cookie ,以及所有cookie元数据信息(可能以列表的形式)?
我是Python的新手,因此非常感谢您的帮助。干杯!
答案 0 :(得分:1)
老实说,我不明白您希望在问题评论中知道什么,但是如果您想通过以下方式解决问题,那将很容易。
所以我的问题是,如何获得服务器发送的3个截然不同的cookie(也许以列表形式)?
import requests
with requests.Session() as s:
resp = s.get("https://github.com")
print(resp.cookies)
#resp.cookies.items()
#resp.cookies.get_dict()
# More details: http://docs.python-requests.org/en/master/_modules/requests/cookies/
<RequestsCookieJar[
<Cookie logged_in=no for .github.com/>,
<Cookie _gh_sess=UHd5aUZ0ZXlBVDVPMitaVVBaWFp0c1p6dFA0TWVSanJzRGgrbU1XbVkxV3VXRW9LeWgwWHpWZ2pOOHFxZmtGaTZpRExpT2NjTHRyK3hHZG5GZjlxTzllbklqK0thQytHYi9HZWsrZ1poZ1ZUakJkRU9OZmJINEh3QUR2N3h3UUh6aVdFTmFCRHlHcVpwWHo1bEM5d25adnhUemJ6Y3pFMUxTbk50Q0M0UUJrVG5hR3kxRUVoUTB2TjdUc2hWbHk3cDJDWUZ4UW85NVRuR09keFJRTlc1QT09LS1RUnZHWUpsQ3BQU0hPZGtsWDAxQXFBPT0%3D--d2bd04e94c369f425fb7e9cc57b5b5499909b140 for github.com/>,
<Cookie has_recent_activity=1 for github.com/>]>
它也可以通过正则表达式(regex101_A regex101_B)提取
import requests, re
with requests.Session() as s:
resp = s.get("https://github.com")
show_cookie = lambda x: [re.findall(r"([^,;\s]*?=.*?(?=;|$))|(\w+(?=;|$|,))",cookie) for cookie in re.findall(r"((?:^|,\s).*?)(?=,\s\S+;|$)",x)]
print(show_cookie(resp.headers.get('Set-Cookie')))
[[('has_recent_activity=1', ''), ('path=/', ''), ('expires=Sat, 29 Dec 2018 14:43:45 -0000', '')], [('logged_in=no', ''), ('domain=.github.com', ''), ('path=/', ''), ('expires=Wed, 29 Dec 2038 13:43:45 -0000', ''), ('', 'secure'), ('', 'HttpOnly')], [('_gh_sess=eHBNWkZscHFMeXJ3NEJUU0VXZlBQaHg0S01rby9MK24xNnFvR3gvVTBsOUJjTWNWenJPZ0RRdk9RNE9ZV2V0MTQ1bTg2NEduY3phSWRrd3l0L252KzBJNkRYZlpjWXh5c2NBZktkWGFsdjZDbEJjTEdhVmZ0YnpldDFHTEpuQzFTcDNNS21sT3BRaHhBVUFqTHQ1cDZyQWNPU005ODY0bFh0MGxCbWI5d2kwait5RlcvVjlUc2FwTTdNRE8wOHZQb0RGak5YbG1ZSDJTM2ZpQmVUUkkrdz09LS11M0ZHem1YYjdWYkVLaWtRMkhscW5nPT0%3D--f778e2d24e96f3386a2da36e2d33d2b73418deed', ''), ('path=/', ''), ('', 'secure'), ('', 'HttpOnly')]]