Search code examples
pythonpython-requestsweather

Requests VS Urllib 2


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

Solution

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

    parsed_json = f.json()