I have been struggling for a while trying to convert some code from an older version of Python. I'm simply trying to run an api lookup from wunderground and I can't get past my errors in python. Here is the error: f = urllib.request.urlopen(fileName) AttributeError: 'module' object has no attribute 'request'
The code is pretty straight forward, I know i"m missing something simple, thanks for any help.
import urllib
import json
key = "xxxxxxxxxxxxxxxxx"
zip = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/" + key + "/geolookup/conditions/q/PA/" + zip + ".json"
f = urllib.request.urlopen(fileName)
json_string = f.read()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print ("Current temperature in %s is: %s % (location, temp_f)")
close()
Sometimes importing a package (e.g. numpy) automatically imports submodules (e.g. numpy.linalg) into its namespace. But that is not the case for urllib. So you need to use
import urllib.request
instead of
import urllib
in order to access the urllib.request module. Alternatively, you could use
import urllib.request as request
in order to access the module as request.
Looking at the examples in the docs is a good way to avoid problems like this in the future.
Since f.read() returns a bytes object, and json.loads expects a str, you'll also need to decode the bytes. The particular encoding depends on what the server decides to send you; in this case the bytes are utf-8 encoded. So use
json_string = f.read().decode('utf-8')
parsed_json = json.loads(json_string)
to decode the bytes.
There is a small typo on the last line. Use
print ("Current temperature in %s is: %s" % (location, temp_f))
to interpolate the string "Current temperature in %s is: %s" with the values (location, temp_f). Note the placement of the quotation mark.
Tip: Since zip is a builtin-function, it is a good practice not to name a
variable zip since this changes the usual meaning of zip making it harder
for others and perhaps future-you to understand your code. The fix is easy: change zip to something else like zip_code.
import urllib.request as request
import json
key = ...
zip_code = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/" + key + "/geolookup/conditions/q/PA/" + zip_code + ".json"
f = request.urlopen(fileName)
json_string = f.read().decode('utf-8')
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print ("Current temperature in %s is: %s" % (location, temp_f))
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