Search code examples
pythonimportnameerror

NameError: name 'urlopen' is not defined


ok this is my last question so i finally found an api that prints good and that works but my problem is im getting errors if someone could look at this for me and tell me whats wrong that would be great

import urllib
import json

request = urlopen("http://api.exmaple.com/stuff?client_id=someid&client_secret=randomsecret")
response = request.read()
json = json.loads(response)
if json['success']:
     ob = json['response']['ob']
     print ("The current weather in Seattle is %s with a temperature of %d") % (ob['weather'].lower(), ob['tempF'])
else:
     print ("An error occurred: %s") % (json['error']['description'])
request.close()

and here is the error

Traceback (most recent call last):
File "thing.py", line 4, in <module>
request = urlopen("http://api.exmaple.com/stuff?client_id=someid&client_secret=randomsecret")
NameError: name 'urlopen' is not defined

Solution

  • You did not import the name urlopen.

    Since you are using python3, you'll need urllib.request:

    from urllib.request import urlopen
    req = urlopen(...)
    

    or explicitly referring to the request module

    import urllib.request
    req = request.urlopen(...)
    

    in python2 this would be

    from urllib import urlopen
    

    or use urllib.urlopen.


    Note: You are also overriding the name json which is not a good idea.