Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 334
apples723 Avatar asked Jun 26 '13 21:06

apples723


3 Answers

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.

like image 97
Elazar Avatar answered Oct 19 '22 13:10

Elazar


Python does not know that the urlopen you refer to (line 4) is the urlopen from urllib. You have two options:

  1. Tell Python that it is - replace urlopen with urllib.urlopen
  2. Tell Python that ALL references to urlopen are the one from urllib: replace the line import urllib to from urllib import urlopen
like image 25
AMADANON Inc. Avatar answered Oct 19 '22 12:10

AMADANON Inc.


it should be:

import urllib
import json

request  = urllib.urlopen("http://api.example.com/endpoint?client_id=id&client_secret=secret")
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()

You didn't specifically import the urlopen() method from the urllib library.

like image 1
msturdy Avatar answered Oct 19 '22 11:10

msturdy