我对使用请求、urlopen和JSONDecoder().decode()感到有点困惑。
目前我有:
hdr = {'User-agent' : 'anything'} # header, User-agent header describes my web browser我假设服务器使用它来确定哪些浏览器是可以接受的?不确定
我的网址是:
url = 'http://wwww.reddit.com/r/aww.json'我设置了一个req变量
req = Request(url,hdr) #request to access the url with header
json = urlopen(req).read() # read json page我尝试在终端中使用urlopen,得到了以下错误:
TypeError: must be string or buffer, not dict # This has to do with me header?
data = JSONDecoder().decode(json) # translate json data so I can parse through it with regular python functions?我不太清楚为什么我会得到TypeError
发布于 2013-11-13 23:56:22
如果查看Request的文档,可以看到构造函数签名实际上是Request(url, data=None, headers={}, …)。因此,第二个参数,即URL后面的参数,是您与请求一起发送的数据。但是,如果要设置标头,则必须指定headers参数。
你可以用两种不同的方式做这件事。要么将None作为数据参数传递:
Request(url, None, hdr)但是,这要求您明确地传递data参数,并且必须确保传递默认值才不会造成任何不必要的影响。因此,您可以告诉Python解释地传递header参数,而不指定data。
Request(url, headers=hdr)https://stackoverflow.com/questions/19966763
复制相似问题