我正试图从网站获取标题,用
JSON编码将其写入文件.
我尝试了两种不同的方法但没有成功.
首先使用urllib2和json
import urllib2
import json
host = ("https://www.python.org/")
header = urllib2.urlopen(host).info()
json_header = json.dumps(header)
print json_header
这样我得到错误:
TypeError: is not
JSON serializable
所以我尝试通过将对象转换为字符串来绕过这个问题 – > json_header = str(标题)
通过这种方式我可以json_header = json.dumps(标题),但输出很奇怪:
“Date: Wed, 02 Jul 2014 13:33:37 GMT\r\nServer: nginx\r\nContent-Type:
text/html; charset=utf-8\r\nX-Frame-Options:
SAMEORIGIN\r\nContent-Length: 45682\r\nAccept-Ranges: bytes\r\nVia:
1.1 varnish\r\nAge: 1263\r\nX-Served-By: cache-fra1220-FRA\r\nX-Cache: HIT\r\nX-Cache-Hits: 2\r\nVary: Cookie\r\nStrict-Transport-Security:
max-age=63072000; includeSubDomains\r\nConnection: close\r\n”
第二次请求
import requests
r = requests.get(“https://www.python.org/”)
rh = r.headers
print rh
{‘content-length’: ‘45682’, ‘via’: ‘1.1 varnish’, ‘x-cache’: ‘HIT’,
‘accept-ranges’: ‘bytes’, ‘strict-transport-security’:
‘max-age=63072000; includeSubDomains’, ‘vary’: ‘Cookie’, ‘server’:
‘nginx’, ‘x-served-by’: ‘cache-fra1226-FRA’, ‘x-cache-hits’: ’14’,
‘date’: ‘Wed, 02 Jul 2014 13:39:33 GMT’, ‘x-frame-options’:
‘SAMEORIGIN’, ‘content-type’: ‘text/html; charset=utf-8’, ‘age’:
‘1619’}
通过这种方式,输出更像JSON,但仍然不行(请参阅”而不是“”和其他类似=和;的东西).
显然有一些(或很多)我没有以正确的方式做.
我试过阅读模块的文档但我无法理解如何解决这个问题.
谢谢您的帮助.