请求VS Urllib 2

时间:2017-01-07 01:14:40

标签: python python-requests weather

在Urllib 2中有一个被调用的“读取”参数。我正在尝试使用请求在python 3中使用此脚本,但我仍然是如此新的使用它,我被绊倒了。我有一种感觉,一旦我弄明白,我可能需要找出其他东西才能使其发挥作用。我想在华氏温度下获得当前的温度。

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))

我收到了追溯错误:

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 个答案:

答案 0 :(得分:1)

请求已经有了获取json的方法,而是使用它。将相关行更改为:

parsed_json = f.json()

答案 1 :(得分:0)

在玩完代码后,我让它工作并打印当前的温度。通过取出我认为是urllib2的副产品的变量parsed_json = json.loads(f)。如果我错了,请告诉我,但它确实有效。

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))