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

PythonPython 3.xUrllib

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

Try this:

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

Solution 2 - Python

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.)

Solution 3 - Python

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).

Solution 4 - Python

I got the same error {AttributeError: 'bytes' object has no attribute 'read'} in python3. This worked for me later without using json:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionParseltongueView Question on Stackoverflow
Solution 1 - PythonMRABView Answer on Stackoverflow
Solution 2 - PythonKatrielView Answer on Stackoverflow
Solution 3 - PythonDog eat cat worldView Answer on Stackoverflow
Solution 4 - PythonBanjaliView Answer on Stackoverflow