# import requests
# def get_weather():
# #设置区域编码,416500表示保靖
# city_code = "416500"
# #构建API请求URL
# url = f"https://hm.baidu.com/hm.gif?hca=B0003C9E07DFB69B&cc=1&cf=copy_link?=&ck=1&cl=24-bit&cp=toutiao_android&cu=client_share&ds=1366x768&vl=324&ep=525834,155641&et=3&ja=0&ln=zh-cn&lo=0<=1705931864&rnd=1032155829&si=30606b57e40fddacb2c26d2b789efbcb&v=1.3.0&lv=2&sn=55977&r=0&ww=1366&u=https://m.tianqi.com/baojing/30/?share_token=2a9c36cf-26e8-4e3e-bc3e-4d267079faba&tt_force_outside=1&tt_from=copy_link&utm_campaign=client_share&utm_medium=toutiao_android&utm_source=copy_link?== {city_code}&key = {your_api_key}"
# # 发起 GET 请求获取天气数据
# response = requests.get(url)
# #解析响应数据
# data = response.json()
# #获取天气描述信息
# weather_description = data["weather"]["description"]
# #获取温度信息
# temperature = data['weather']['temperature']
# #获取天气状况图标的URL
# weather_icon_url = data["weather"]["icon"]
# return weather_description,temperature,weather_icon_url
# #获取天气描述信息
# weather_description, temperature, weather_icon_url = get_rweathe()
# #打印天气信息
# print(f"天气描述:{weather_description}")
# print(f"温度:{temperature}")
# print(f"天气图标URL:{weather_icon_url}")
# 导入模块
import csv
import requests
from lxml import etree
# 网页网址:https://m.tianqi.com/baojing/30
# 创建对应csv表格存储天气数据
#CLOSE = f.close()
f = open('baojing.csv', 'w', newline="", encoding="utf-8")
write = csv.writer(f)
write.writerow(["日期", "天气", "温度"])
# 网址
url = "https://m.tianqi.com/baojing/30"
# 请求头参数
headers = {
'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
'referer': 'https://m.tianqi.com/baojing/'
}
# 发送请求获取数据
res = requests.get(url, headers=headers).text
tree = etree.HTML(res)
# 匹配数据,包含需要获取的相关数据
datas = tree.xpath('//*[@class="weatherbox"]//dl')
for i in datas:
# 匹配数据
date = i.xpath("./dd[1]/text()")[0].replace("\xa0", "") # 匹配日期
weather = i.xpath("./dd[3]/text()")[0] # 匹配天气
temperature = ''.join(i.xpath("./dd[4]//text()")) # 匹配温度
# 输出操作:
print(f"日期:{date},天气:{weather},温度:{temperature}")
# 添加一行数据到表格中
write.writerow([date, weather, temperature])
# 关闭文件
#f.close()
2024年的第一场雪
于 2024-02-25 21:37:27 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)