我对使用 Request、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
最佳答案
如果你查看 Request
的文档,您可以看到构造函数签名实际上是 Request(url, data=None, headers={}, …)
。因此,第二个参数(URL 后面的参数)是您随请求发送的数据。但如果您想设置 header ,则必须指定 headers
参数。
您可以通过两种不同的方式来完成此操作。您可以传递 None
作为数据参数:
Request(url, None, hdr)
但是,这需要您显式传递 data
参数,并且必须确保传递默认值,以免造成任何不良影响。因此,您可以告诉 Python 显式传递 header
参数,而不指定 data
:
Request(url, headers=hdr)
关于python - urlopen() 出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19966763/