将Cookie字符串转换为Python字典 [英] Converting cookie string into Python dict
问题描述
在Fiddler中,我捕获了一个HTTPS请求,其中包含从客户端发送的以下cookie字符串(在Inspectors> Raw中可见):
In Fiddler, I captured an HTTPS request with the following cookie string sent from the client (visible in 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进行了一些修改,以使读者无法将其用于邪恶目的!).
I'd like to use this cookie in a Python Requests request. (I modified the cookie slightly, so that it can't be used by readers for nefarious purposes!).
但是,请求似乎使用词典格式来发送Cookie ,并且在将上述字符串/blob转换为字典格式时遇到麻烦.
However, Requests appears to use a dictionary format for sending cookies, and I'm having trouble converting the above string/blob into a dictionary format.
我的问题是:
- 是否有一种自动的方法可以将字符串(例如我在Fiddler中捕获的cookie)转换为Python中的字典?
推荐答案
您应该能够使用标准Python库中可用的SimpleCookie
:
You should be able to use SimpleCookie
which is available in the standard Python library:
from http.cookies import SimpleCookie
rawdata = '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'
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 = {}
for key, morsel in cookie.items():
cookies[key] = morsel.value
如果您使用的是Python 2,则必须从Cookie
而不是http.cookies
导入.
If you are using Python 2, you will have to import from Cookie
instead of http.cookies
.
文档:
https://docs.python.org/2/library/cookie.html
https://docs.python.org/3/library/http. cookies.html
这篇关于将Cookie字符串转换为Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!