python3中要怎么实现getWeather方法
来源:3-2 如何实现可迭代对象和迭代器对象(2)

端碗吹水
2018-01-20
from urllib import request
import json
def getWeather(city):
url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
resu = request.urlopen(url)
data = json.loads(resu)['data']['forecast'][0]
return '%s: %s , %s ' % (city, data['low'], data['hight'])
print(getWeather('北京'))
报错:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 23-24: ordinal not in range(128)
1回答
-
端碗吹水
提问者
2018-01-20
已解决,附上python3代码如下:
from urllib import request
import urllib
import json
import gzip
def getWeather(city):
url_str = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
# 转换URL的中文,safe参数指定哪些符号不转换
url = urllib.parse.quote(url_str, safe='/:?=')
resp = request.urlopen(url).read()
# 由于返回的的数据是gzip的压缩格式,所以需要解压返回的数据
resp = gzip.decompress(resp)
# 将字节转换成字符串,编码设置为utf-8
json_data = str(resp, encoding = 'utf-8')
# 解析json数据
data = json.loads(json_data)['data']['forecast'][0]
return '%s: %s , %s ' % (city, data['low'], data['high'])
print(getWeather('北京'))
print(getWeather('长春'))
112018-03-14
相似问题