蟒蛇; urllib错误:AttributeError:'bytes'对象没有属性'read'

Par*_*gue 26 python urllib python-3.x

注意:这是Python 3,没有urllib2.此外,我已经尝试使用json.loads(),我收到此错误:

TypeError: can't use a string pattern on a bytes-like object
Run Code Online (Sandbox Code Playgroud)

如果我使用json.loads()并从响应中删除.read(),我会收到此错误:

TypeError: expected string or buffer
Run Code Online (Sandbox Code Playgroud)

>

import urllib.request
import json

response = urllib.request.urlopen('http://www.reddit.com/r/all/top/.json').read()
jsonResponse = json.load(response)

for child in jsonResponse['data']['children']:
    print (child['data']['title'])
Run Code Online (Sandbox Code Playgroud)

不起作用......我不明白为什么.

MRA*_*RAB 64

试试这个:

jsonResponse = json.loads(response.decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)


Kat*_*iel 13

使用json.loadsjson.load.

(load从类似文件的对象加载,loads从字符串加载.所以你也可以省略.read()调用.)