中国天气网的API接口http://www.weather.com.cn/data/sk/城市代码.html
广州的城市代码为 101280101 韶关的城市代码为 101280201
中国天气网广州天气的API接口为 http://www.weather.com.cn/data/sk/101280101.html
代码如下:
#!/usr/bin/env python3
from urllib import request
import json
city_web = 'http://www.weather.com.cn/data/sk/101280101.html'
r = request.urlopen(city_web) ##使用request模块,把请求结果放到r里面
data = r.read() ##读取r里面的数据赋值给data,此时是一个json格式的字符串
print(json.loads(data)) ##用json模块,这里可以理解为,可以把一个json格式的字符串,转换成字典
r.close()
得到的结果如下:
{'weatherinfo': {'city': '广州', 'cityid': '101280101', 'temp': '26.6', 'WD': '东南风','WS': '小于3级', 'SD': '83%', 'AP': '1001.4hPa', 'njd': '暂无实况', 'WSE': '<3','time': '17:50', 'sm': '1.7', 'isRadar': '1', 'Radar': 'JC_RADAR_AZ9200_JB'}}
看到这里,结果是一个字典。
扩展一下脚本。运行脚本,可以让用户选择查询不同城市的天气
脚本如下:
#!/usr/bin/env python3
from urllib import request
import json
def get_info(city_code):
city_web = 'http://www.weather.com.cn/data/sk/%s.html' % city_code #传入的变量生成对应的url
r = request.urlopen(city_web) #得到一个json格式的数据
data = r.read() #读取json格式的数据,赋值给data
data = json.loads(data) #用json模块,把数据转换成python识别的字符
output = '风向:%s, 风力: %s, 温度:%s, 湿度:%s' % (
data['weatherinfo']['WD'],
data['weatherinfo']['WS'],
data['weatherinfo']['temp'],
data['weatherinfo']['SD']
)
return output
if __name__ == '__main__':
city_code = {0: '101280101', 1: '101280201'} ##定义一个字典,存放城市代码
prompt = '''(0)查询广州的天气情况 ##定义一个显示栏
(1)查询韶关的天气情况
请选择你要的功能,输入0/1: '''
choice = int(input(prompt)) #用户输入的结果转换为数字
print(get_info(city_code[choice])) #当choice为0时,相当于get_info(101280101),给函数传入一个变量
使用requests模块实现以上功能,代码如下:
#!/usr/bin/env python3
import requests
def get_info(city_code):
city_web = 'http://www.weather.com.cn/data/sk/%s.html' % city_code
r = requests.get(city_web)
r.encoding = 'utf8'
data = r.json()
output = '风向:%s, 风力: %s, 温度:%s, 湿度:%s' % (
data['weatherinfo']['WD'],
data['weatherinfo']['WS'],
data['weatherinfo']['temp'],
data['weatherinfo']['SD']
)
return output
if __name__ == '__main__':
city_code = {0: '101280101', 1: '101280201'}
prompt = '''(0)查询广州的天气情况
(1)查询韶关的天气情况
请选择你要查询的地区,选择0/1:'''
choice = int(input(prompt))
print(get_info(city_code[choice]))