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

前端 未结 4 746
一整个雨季
一整个雨季 2020-12-14 00:39

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-         


        
相关标签:
4条回答
  • 2020-12-14 01:02

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

    0 讨论(0)
  • 2020-12-14 01:06

    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'))
    
    0 讨论(0)
  • 2020-12-14 01:11

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

    0 讨论(0)
  • 2020-12-14 01:15

    Try this:

    jsonResponse = json.loads(response.decode('utf-8'))
    
    0 讨论(0)
提交回复
热议问题