Python 获取天气信息

测试环境

树莓派cm4 官方64位系统(Debian 10)

Windows 11 专业工作站版 21H2

________________________________________________

Python 3.9.10

requests 2.27.1

API 接口

返回结果为 XML 格式

city= 后指定城市名即可

http://wthrcdn.etouch.cn/WeatherApi?city=

开发

主要是对下图中部分信息进行解析

"""
Copyright (C) 2022 IYATT-yx iyatt@iyatt.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

"""
天气信息获取
"""

import requests
from urllib.parse import urlencode
from xml.dom.minidom import parseString


city = '重庆'
r = requests.get('http://wthrcdn.etouch.cn/WeatherApi?' + urlencode({'city':city}))
if r.status_code != 200:
    print('请求数据失败!')
    exit()
xml_text = r.text

doc = parseString(xml_text)
root = doc.documentElement

today_weather = root.getElementsByTagName('forecast')[0].childNodes[0]  # 今天
date = today_weather.getElementsByTagName('date')[0].childNodes[0].nodeValue # 日期
high = ''.join(list(filter(str.isdigit, today_weather.getElementsByTagName('high')[0].childNodes[0].nodeValue)))  # 最高温度
low = ''.join(list(filter(str.isdigit, today_weather.getElementsByTagName('low')[0].childNodes[0].nodeValue)))  # 最低温
day = today_weather.getElementsByTagName('day')[0].getElementsByTagName('type')[0].childNodes[0].nodeValue  # 白天天气
night = today_weather.getElementsByTagName('night')[0].getElementsByTagName('type')[0].childNodes[0].nodeValue  # 晚上天气
print('日期: {}'.format(date))
print('温度: {}~{} ℃'.format(low, high))
print('白天: {}\t晚上:{}'.format(day, night))

print(40 * '-')

tomorrow_weather = root.getElementsByTagName('forecast')[0].childNodes[1]  # 明天 
date = tomorrow_weather.getElementsByTagName('date')[0].childNodes[0].nodeValue
high = ''.join(list(filter(str.isdigit, tomorrow_weather.getElementsByTagName('high')[0].childNodes[0].nodeValue)))
low = ''.join(list(filter(str.isdigit, tomorrow_weather.getElementsByTagName('low')[0].childNodes[0].nodeValue)))
day = tomorrow_weather.getElementsByTagName('day')[0].getElementsByTagName('type')[0].childNodes[0].nodeValue
night = tomorrow_weather.getElementsByTagName('night')[0].getElementsByTagName('type')[0].childNodes[0].nodeValue
print('日期: {}'.format(date))
print('温度: {}~{} ℃'.format(low, high))
print('白天: {}\t晚上:{}'.format(day, night))