2024年的第一场雪

本文介绍了如何使用Python的requests库和XPath技术从TianqiAPI获取北京的天气描述、温度和图标URL,然后将数据存储在CSV文件中的过程。
摘要由CSDN通过智能技术生成
# 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&lt=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()

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bug_Mr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值