gpt4 book ai didi

python - 将 cookie 字符串转换为 Python 字典

转载 作者:太空狗 更新时间:2023-10-29 19:32:55 35 4
gpt4 key购买 nike

在 Fiddler 中,我捕获了一个 HTTPS 请求,其中包含从客户端发送的以下 cookie 字符串(在 Inspectors > Raw 中可见):

Cookie: devicePixelRatio=1; ident=exists; __utma=13103r6942.2918; __utmc=13103656942; __utmz=13105942.1.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); mp_3cb27825a6612988r46d00tinct_id%22%3A%201752338%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fwww.pion_created_at%22%3A%20%222015-08-03%22%2C%22platform%22%3A%20%22web%22%2C%%22%3A%20%%22%7D; t_session=BAh7DUkiD3Nlc3NpbWVfZV9uYW1lBjsARkkiH1BhY2lmaWMgVGltZSAoVVMgJiBDYW5hZGEpBjsAVEkiFXNpZ25pbl9wZXJzb25faWQGOwBGaQMSvRpJIhRsYXN0X2xvZ2luX2RhdGUGOwBGVTogQWN0aXZlU3VwcG9ydDo6VGltZVdpdGhab25lWwhJdToJVGltZQ2T3RzAAABA7QY6CXpvbmVJIghVVEMGOwBUSSIfUGFjaWZpZWRfZGFzaGJvYXJkX21lc3NhZ2UGOwBGVA%3D%3D--6ce6ef4bd6bc1a469164b6740e7571c754b31cca

我想在 Python Requests 请求中使用此 cookie。 (我稍微修改了 cookie,这样它就不会被读者用于恶意目的!)。

但是,Requests 似乎使用了 dictionary format for sending cookies ,我无法将上述字符串/blob 转换为字典格式。

我的问题是:

  • 有没有一种方法可以自动将字符串(比如我在 Fiddler 中捕获的 cookie)转换为 Python 中的字典?

最佳答案

您应该能够使用标准 Python 库中提供的 SimpleCookie:

from http.cookies import SimpleCookie

rawdata = 'devicePixelRatio=1; ident=exists; __utma=13103r6942.2918; __utmc=13103656942; __utmz=13105942.1.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); mp_3cb27825a6612988r46d00tinct_id%22%3A%201752338%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Fwww.pion_created_at%22%3A%20%222015-08-03%22%2C%22platform%22%3A%20%22web%22%2C%%22%3A%20%%22%7D; t_session=BAh7DUkiD3Nlc3NpbWVfZV9uYW1lBjsARkkiH1BhY2lmaWMgVGltZSAoVVMgJiBDYW5hZGEpBjsAVEkiFXNpZ25pbl9wZXJzb25faWQGOwBGaQMSvRpJIhRsYXN0X2xvZ2luX2RhdGUGOwBGVTogQWN0aXZlU3VwcG9ydDo6VGltZVdpdGhab25lWwhJdToJVGltZQ2T3RzAAABA7QY6CXpvbmVJIghVVEMGOwBUSSIfUGFjaWZpZWRfZGFzaGJvYXJkX21lc3NhZ2UGOwBGVA%3D%3D--6ce6ef4bd6bc1a469164b6740e7571c754b31cca'
cookie = SimpleCookie()
cookie.load(rawdata)

# Even though SimpleCookie is dictionary-like, it internally uses a Morsel object
# which is incompatible with requests. Manually construct a dictionary instead.
cookies = {k: v.value for k, v in cookie.items()}

如果您使用的是 Python 2,则必须从 Cookie 而不是 http.cookies 导入。

文档:

https://docs.python.org/2/library/cookie.html

https://docs.python.org/3/library/http.cookies.html

关于python - 将 cookie 字符串转换为 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32281041/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com