我已经挣扎了一段时间,试图从旧版本的Python中转换一些代码。我只是简单地尝试从wunderground运行一个api查找,而我无法通过我在python中的错误。错误如下:f= urllib.request.urlopen(fileName) AttributeError:'module‘对象没有'request’属性
代码非常简单,我知道我遗漏了一些简单的东西,谢谢你的帮助。
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()发布于 2015-07-05 05:29:27
有时导入包(例如numpy)会自动将子模块(例如numpy.linalg)导入到其名称空间中。但urllib并非如此。所以你需要使用
import urllib.request而不是
import urllib以便访问urllib.request模块。或者,您可以使用
import urllib.request as request以便以request身份访问该模块。
查看examples in the docs是避免将来出现类似问题的好方法。
由于f.read()返回一个bytes对象,而json.loads需要一个str,因此还需要对字节进行解码。具体的编码取决于服务器决定发送给您的内容;在本例中,字节是utf-8编码的。所以请使用
json_string = f.read().decode('utf-8')
parsed_json = json.loads(json_string)对字节进行解码。
最后一行有一个小的打字错误。使用
print ("Current temperature in %s is: %s" % (location, temp_f))使用值(location, temp_f)对字符串"Current temperature in %s is: %s"进行插值。请注意引号的位置。
提示:由于zip是一个内置函数,所以最好不要将变量命名为zip,因为这会改变zip的通常含义,使其他人甚至将来的您更难理解您的代码。解决方法很简单:将zip更改为其他名称,如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))发布于 2015-07-05 06:06:45
我建议使用requests library Python HTTP for Humans.,下面的代码可以在python2或3上运行:
import requests
key = "xxxxxxxxxxx"
# don't shadow builtin zip function
zip_code = input('For which ZIP code would you like to see the weather? ')
fileName = "http://api.wunderground.com/api/{}/geolookup/conditions/q/PA/{}.json".format(key, zip_code)
parsed_json = requests.get(fileName).json()
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
# pass actual variables and use str.format
print ("Current temperature in {} is: {}%f".format(location, temp_f))获取json是简单的requests.get(fileName).json(),使用str.format是首选的方法,我发现它不太容易出错,而且与旧的printf样式格式化相比,它的功能也要丰富得多。
通过一个示例运行,您可以看到它在2和3下都可以工作:
:~$ python3 weat.py
For which ZIP code would you like to see the weather? 12212
Current temperature in Albany is: 68.9%f
:~$ python2 weat.py
For which ZIP code would you like to see the weather? 12212
Current temperature in Albany is: 68.9%fhttps://stackoverflow.com/questions/31225132
复制相似问题