Requests VS Urllib 2

1k views Asked by At

In Urllib 2 there is a "read" argument that gets called. I am trying to take this script in python 3 using requests but I'm still so new using it that I get tripped up. I have a feeling that once I get this figured out that I might need to figure something else out to make it work. I am trying to get the current temp in Fahrenheit.

import requests
import json
f = requests.get('http://api.wunderground.com/api/mykey/geolookup/conditions/q/LA/tickfaw.json')
json_string = f.json()
parsed_json = json.loads(f)
location = parsed_json[str('location')][str('city')]
temp_f = parsed_json['current_observation']['temp_f']
print("Current temperature in %s is: %s" % (location, temp_f))

I am getting a traceback error:

Traceback (most recent call last):
 File "C:/Users/jerem/PycharmProjects/webscraper/scratch.py", line 5, in <module>
parsed_json = json.loads(f)
 File "C:\Users\jerem\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'Response'

Process finished with exit code 1
2

There are 2 answers

0
Natecat On BEST ANSWER

Requests already has a method to get json, use that instead. Change the relevant line to:

parsed_json = f.json()
0
Kamikaze_goldfish On

After playing with the code I got it to work and print the current temp. By taking out the variable parsed_json = json.loads(f) which what I assume to be a by-product of urllib2. If I am wrong let me know but it is working.

import requests
import json
f = requests.get('http://api.wunderground.com/api/mykey/geolookup/conditions/q/LA/tickfaw.json')
json_string = f.json()
location = json_string[str('location')][str('city')]
temp_f = json_string['current_observation']['temp_f']
print("Current temperature in %s is: %s" % (location, temp_f))