[Python]requests 得到headers解析为dic
2018-10-11 本文已影响310人
_小老虎_
我们看看headers的type,是CaseInsensitiveDict类.
r = requests.get("http:...")
In [99]: type(r.headers)
Out[99]: requests.structures.CaseInsensitiveDict
不能直接拿来用
- 解决方法
In [96]: json.dumps(dict(r.headers))
Out[96]: '{"x-powered-by": "PHP/5.3.3", "transfer-encoding": "chunked", "content-encoding": "gzip", "server": "nginx/1.8.0", "connection": "keep-alive", "date": "Mon, 25 Jan 2016 09:56:54 GMT", "content-type": "text/html; charset=UTF-8", "x-pingback": "http://xiaorui.cc/xmlrpc.php"}'
In [97]: json.loads(json.dumps(dict(r.headers)))
Out[97]:
{u'connection': u'keep-alive',
u'content-encoding': u'gzip',
u'content-type': u'text/html; charset=UTF-8',
u'date': u'Mon, 25 Jan 2016 09:56:54 GMT',
u'server': u'nginx/1.8.0',
u'transfer-encoding': u'chunked',
u'x-pingback': u'http://xiaorui.cc/xmlrpc.php',
u'x-powered-by': u'PHP/5.3.3'}