Chinaunix首页 | 论坛 | 博客
  • 博客访问: 337261
  • 博文数量: 100
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 521
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-31 11:37
个人简介

活到老,学到老

文章分类

全部博文(100)

文章存档

2018年(1)

2017年(2)

2016年(11)

2015年(82)

2014年(4)

我的朋友

分类: Python/Ruby

2016-07-23 10:53:02

天气接口

中国天气weather.com
(六天预报)

(实时天气信息)

其中101110101是城市的代码,获得城市代码进入


在搜索框上输入你要需要获得天气的城市,点击查询,即可在地址栏获得相应城市编号,然后替换


返回的实时天气的json:

  1. {"weatherinfo":{"city":"北京","cityid":"101010100","temp":"18","WD":"东南风","WS":"1级","SD":"17%","WSE":"1","time":"17:05","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1011","rain":"0"}}
代码:


#!/usr/local/bin/python3
#coding=utf-8


#         实时
#   全天
#     六天


## 英文
##
##&hl=zh-cn 中文


import os, io, sys, re, time, base64, json
import webbrowser, urllib.request


#城市
city_list=[
    {'code':"101010100",'name':"北京"},
    {'code':"101091001",'name':"邯郸"}
]


#返回dict类型: info_dict = {'image': imgPath, 'message': content}
def getCityWeather_Realtime(cityID):
    url=""+str(cityID)+".html"
    try:
        stdout=urllib.request.urlopen(url)
        weatherInfo=stdout.read().decode('utf-8')


        #print(weatherInfo)
        jsonDatas=json.loads(weatherInfo)


        city = jsonDatas["weatherinfo"]["city"] #城市
        temp = jsonDatas["weatherinfo"]["temp"] #温度
        fx = jsonDatas["weatherinfo"]["WD"]  #风向
        fl = jsonDatas["weatherinfo"]["WS"] #风力
        sd = jsonDatas["weatherinfo"]["SD"] #相对湿度
        tm = jsonDatas["weatherinfo"]["time"] #发布时间


        content ="#" +city + "#" + " " +temp + "℃ " + fx + \
                    fl + " " + " 相对湿度" + sd + " " +"发布时间:" +tm


        info_dict ={'image':"",'message':content}


    except (SyntaxError) as err:
        print(">>>> SyntaxError: " + err.args)
    except:
        print(">>>> OtherError: ")
    else:
        return info_dict
    finally:
        None


def main():
    for city in city_list:
        title ="【实时】"
        info_dict =getCityWeather_Realtime(city['code'])
        print(title + info_dict['message'])


if __name__ == '__main__':
    main()



运行结果:
  1. 【实时】#北京# 18℃ 东南风1级 相对湿度17% 发布时间:17:05
  2. 【实时】#邯郸# 21℃ 南风3级 相对湿度19% 发布时间:17:05






阅读(1464) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~