设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: crossin先生
打印 上一主题 下一主题

【Python 第44课】 查天气(2)

  [复制链接]

0

主题

0

好友

18

积分

新手上路

Rank: 1

楼主
发表于 2018-2-12 22:19:17 |显示全部楼层
crossin先生 发表于 2016-4-29 11:02
发现 wthrcdn.etouch.cn 这个站的返回接口用了 gzip 压缩数据。所以你那个不是编码问题,而是数据被压缩 ...

老师,我用的Python3,自己改了一下代码,现在又出现这个新问题了,请问怎么解决啊
  1. import urllib.request
  2. import json
  3. import urllib
  4. import io
  5. import gzip
  6. print('你想查哪个城市的天气')
  7. place=urllib.parse.quote(input())
  8. url='http://wthrcdn.etouch.cn/weather_mini?city=%s'%place
  9. content=urllib.request.urlopen(url).read()
  10. #print(content)
  11. buf=io.StringIO(content)
  12. f=gzip.GzipFile(fileobj=buf)
  13. data=f.read()
  14. print(data)

  15. Traceback (most recent call last):
  16.   File "C:/Python3/weather.py", line 12, in <module>
  17.     buf=io.StringIO(content)
  18. TypeError: initial_value must be str or None, not bytes

复制代码
回复

使用道具 举报

0

主题

0

好友

18

积分

新手上路

Rank: 1

沙发
发表于 2018-2-13 21:43:58 |显示全部楼层
crossin先生 发表于 2018-2-12 22:30
拿到content后转化一下,content = content.decode('utf8')

老师,我按照您说的改了之后,print(content)时,又报错Traceback (most recent call last):
  File "C:\Python3\weather.py", line 12, in <module>
    content=content.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

我上网查说是去掉'Accept-Encoding':' gzip, deflate',但是程序里本来就没这句话啊。
附上代码
  1. import urllib.request
  2. import json
  3. import urllib
  4. import io
  5. import gzip
  6. print('你想查哪个城市的天气')
  7. place=urllib.parse.quote(input())
  8. url='http://wthrcdn.etouch.cn/weather_mini?city=%s'%place
  9. content=urllib.request.urlopen(url).read()
  10. content=content.decode('utf-8')
  11. print (content)
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-22 07:12 , Processed in 0.029071 second(s), 24 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部