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
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.
Python does not know that the urlopen
you refer to (line 4) is the urlopen
from urllib
. You have two options:
urlopen
with urllib.urlopen
urlopen
are the one from urllib
: replace the line import urllib
to from urllib import urlopen
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With