2022年 11月 7日

使用Python获取天气信息

使用Python通过天气网站的API接口获取天气信息

1、使用python获取城市天气信息的方法一般有两种,一种是通过爬虫爬取天气网站的信息,然后再分析HTML提取天气信息,这种方式比较复杂,需要用户了解天气网站和后台交互信息的方式,模拟网站提交城市信息,然后后台才能返回用户想要的网页数据,再之后还要对HTML进行解析从众多代码中提取想要的信息。
2、另一种比较简单方便的方式则是通过通过天气预报网站提供的API,通过使用API省去了分析HTML和模拟网站提交城市的复杂步骤

代码运行结果图

在这里插入图片描述

代码演示

def getWeather(name):
    url = 'http://wthrcdn.etouch.cn/weather_mini'
    response = requests.get(url, {'city': name})
    result = json.loads(response.content.decode())
    print('city:', result.get('data').get('city'))
    data = result.get('data').get('yesterday')
    print(data.get('date'), '\t', data.get('high'), '\t', data.get('low'), '\t', data.get('type'), '\t', data.get('fx'), '\t',
          data.get('fl').replace('<![CDATA[', '').replace(']]>', ''))
    data = result.get('data').get('forecast')
    for i in data:
        print(i.get('date'), '\t', i.get('high'), '\t', i.get('low'), '\t', i.get('type'), '\t', i.get('fengxiang'), '\t',
          i.get('fengli').replace('<![CDATA[', '').replace(']]>', ''))


if __name__ == '__main__':
    print(getWeather('深圳'))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

作者本人为了输出的信息更为美观,使用制表符输出!