AttributeError:“str”对象没有“read”Python属性。。

2024-04-26 00:54:28 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

import urllib, json, unicodedata, webbrowser

url = "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=10&format=json"



response = urllib.urlopen(url)
data = json.loads(response.read())
while True:
    if data.get("data") == None:
        print "server error, trying again"
        data = json.loads(response.read())
    else:
        break

for a in data["query"]["random"]:
    print a["title"]
    userread = raw_input("Would you like to read this article? y/n")
    if userread.lower() == "y":
        articleid = a["id"]
        articleurl = "https://en.wikipedia.org/?curid=" + articleid
        webbrowser.open_new(articleurl)

现在,for循环并不那么重要,因为我遇到了这个错误:

  File "randomwiki.py", line 12, in <module>
    data = json.loads(response.read())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

url是Wikipedia在JSON中的随机页面文章API。我不确定是什么问题。有什么帮助吗?


Tags: inpyjsonurlreaddatarawresponse
1条回答
网友
1楼 · 发布于 2024-04-26 00:54:28

urllib.read函数接收字节对象,但json.loads接收字符串。 如果需要,可以使用requests模块:

import requests
response = requests.get(url)
data = json.loads(response.read())

当然,也可以对urllib.read函数的输出进行解码。

data = json.loads(response.read().decode())

相关问题 更多 >