设为首页收藏本站

Crossin的编程教室

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

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

  [复制链接]

0

主题

0

好友

14

积分

新手上路

Rank: 1

楼主
发表于 2018-12-19 21:49:58 |显示全部楼层
crossin 先生好~新手上路,遇到了两个问题
用的访问地址是http://wthrcdn.etouch.cn/weather_mini?city=北京和http://wthrcdn.etouch.cn/weather_mini?citykey=101010100
第一个问题是
我用citycode是成功的,但是最后出来的风向里面有一些符号,不知道是什么意思
第二个问题是
我用城市名访问时就会失败
下面是我的代码,和用城市代码访问的区别就是没有读取city.py,其他都是一样的,求老师指点~~

#-*-coding:gbk-*-
import json
import urllib.request
import gzip


cityname=input('你想查哪个城市的天气?\n')
if cityname:
    url=('http://wthrcdn.etouch.cn/weather_mini?citykey=%s'%cityname)
    content=urllib.request.urlopen(url).read()
    data = gzip.decompress(content)#解压缩为json
    data_c=json.loads(data)#转换为中文
    result=data_c['data']
    str_yd=result['yesterday']
    str_fc=result['forecast']
    print('今日:\n温度:%s℃ 空气质量指数:%s\n建议:%s\n'%(result['wendu'],
                                            result['aqi'],result['ganmao']))
    print('昨日:\n%s %s %s %s %s %s\n'%(str_yd['date'],str_yd['type'],
                                      str_yd['high'],str_yd['low'],str_yd['fl'],str_yd['fx']))
    print('未来5天:')
    for day in str_fc:        
        print('%s %s %s %s %s %s'%(day['date'],day['type'],day['high'],
                                   day['low'],day['fengli'],day['fengxiang']))

else:
    print('没有你想要查询的城市。')

查天气失败.png (26.2 KB, 下载次数: 453)

查天气失败.png

查天气.png (14.47 KB, 下载次数: 442)

查天气.png

回复

使用道具 举报

0

主题

0

好友

14

积分

新手上路

Rank: 1

沙发
发表于 2018-12-20 11:34:57 来自手机 |显示全部楼层
crossin先生 发表于 2018-12-19 23:01
那个符号是他数据的问题,你可以手动处理一下

城市名需用用 utf8进行编码后,通过 urlquote 转成url编码 ...

谢谢老师!两个问题都已经解决了!我用的是python3 ,在网上查了发现默认源码就是utf8,所以加了一行urllib.parse.quote就可以了!
老师回得好快,太谢谢啦~~☺
回复

使用道具 举报

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

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

GMT+8, 2024-5-3 08:07 , Processed in 0.020163 second(s), 26 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部