gpt4 book ai didi

python - urlopen() 的类型错误

转载 作者:行者123 更新时间:2023-11-28 22:52:53 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com