python - urlopen() 出现类型错误

标签 python

我对使用 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/

相关文章:

python os.rename ""当文件已经存在时无法创建文件

python - 如何在 Django 中使用配置文件注册不同类型的用户?

python - 在 Flask 或 WSGI 中打印原始 HTTP 请求

python - django-rq Redis 客户端发送了 AUTH,但没有设置密码

python - 如何防止 Python 打印添加换行符或空格?

python - pyplot : Position of cursor not shown

python - 从右边开始每隔第 n 个字符拆分字符串?

python - 使用 aiohttp 时出现 "RuntimeError: <_overlapped.Overlapped object> still has pending operation at deallocation"

python - 使用 python 从不同长度的元组列表中删除重复项

python - Google 应用引擎引用属性关系