要使用Python获取和展示天气信息,你可以遵循以下步骤:
获取天气数据
使用`requests`库发送HTTP请求到天气API服务,例如和风天气API(`www.heweather.com`),获取天气数据。
```python
import requests
api_key = "你的和风天气API密钥"
base_url = "http://devapi.qweather.com/v7/weather/now"
params = {
"location": "城市名",
"key": api_key
}
response = requests.get(base_url, params=params)
data = response.json()
处理数据解析返回的JSON数据,提取所需的天气信息。```pythonweather_info = data['now']
city_name = weather_info['location']['name']
temperature = weather_info['temp']
text_desc = weather_info['text']
展示数据
使用`jinja2`模板引擎创建HTML模板,将天气信息插入到模板中,然后渲染模板。

```python
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('weather.html')
html_out = template.render(city_name=city_name, temperature=temperature, text_desc=text_desc)
发送邮件(可选)如果需要,可以使用`smtplib`库发送包含天气信息的邮件。```pythonimport smtplib
from email.mime.text import MIMEText
msg = MIMEText(html_out)
msg['Subject'] = f"当前城市天气 - {city_name}"
msg['From'] = "你的邮箱地址"
msg['To'] = "收件人邮箱地址"
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login(msg['From'], '你的邮箱密码')
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
定时任务(可选)
使用`crontab`设置定时任务,定期执行脚本以获取和发送天气信息。
```bash
编辑crontab文件
crontab -e
添加以下行以每天凌晨执行脚本
0 0 * * * /usr/bin/python3 /path/to/your/weather_script.py
以上步骤展示了如何使用Python获取和展示天气信息的基本流程。你可以根据实际需求调整代码,比如添加用户界面、错误处理、多城市支持等。
