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('长春'))


1
1
小鲁锅的进阶之路
确实,返回的数据必须经过解压缩,才能转化成功。不过,你是怎么看出来爬取的数据是解压形式呢?你是如何判断的?
2018-03-14
共1条回复

Python高效编程技巧实战

精选50个Python案例,源自实战,全面提升Python编程能力

2582 学习 · 360 问题

查看课程