Pyhton3 使用request模块,requests模块,分别实现天气预报查询

中国天气网的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]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值