Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

Note: This is Python 3, there is no urllib2. Also, I've tried using json.loads(), and I get this error:

TypeError: can't use a string pattern on a bytes-like object

I get this error if I use json.loads() and remove the .read() from response:

TypeError: expected string or buffer

>

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'])

Does not work... I have no idea why.

回答1:

Try this:

jsonResponse = json.loads(response.decode('utf-8'))


回答2:

Use json.loads not json.load.

(load loads from a file-like object, loads from a string. So you could just as well omit the .read() call instead.)



回答3:

I'm not familiar with python 3 yet, but it seems like urllib.request.urlopen().read() returns a byte object rather than string.

You might try to feed it into a StringIO object, or even do a str(response).



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!