0

I'm fairly new to Python and I'm trying to execute a HTTP Request to a URL that returns JSON. The code, I have is:

url = "http://myurl.com/"
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
data = response.read()

I'm getting an error reading: "'bytes' object has no attribute 'read'". I searched around, but haven't found a solution. Any suggestions?

user1496624
  • 107
  • 1
  • 2
  • 12
  • 2
    This can't be your real code. In your real code, try `print(type(response))` and/or `print(repr(response))` to see what you've got in place of the `http.client.HTTPResponse` that this code returns. And then show us your real code and we can show you why you've got that. – abarnert Oct 20 '14 at 20:59
  • The most obvious mistake that would cause this is `response = urllib.request.urlopen(req).read()`, so you're calling `read()` on the result of `read()`, but there are countless other ways you could do this, and we can't guess which one you did without an [MCVE](http://stackoverflow.com/help/mcve). – abarnert Oct 20 '14 at 20:59
  • duplicate http://stackoverflow.com/questions/6862770/python-3-let-json-object-accept-bytes-or-let-urlopen-output-strings – Michele d'Amico Oct 20 '14 at 21:23

1 Answers1

0

You may find the requests library easier to use:

import requests
data = requests.get('http://example.com').text

or, if you need the raw, undecoded bytes,

import requests
data = requests.get('http://example.com').content
Robᵩ
  • 163,533
  • 20
  • 239
  • 308