爬取天气数据并解析温度值

一、概述

获取北京周边城区的天气数据,链接如下:http://www.weather.com.cn/weather1d/101010100.shtml#input

 

最终需要得到以下数据:

[
  {'location': '香河', 'high': '36', 'low': '23°C'},
  ...
]

 

二、分析页面

地区

可以发现数据在 id="around"这个div里面,地区的值在a标签中。

 

 

那么xpath规则为:

//*[@id="around"]//a[@target="_blank"]/span/text()

效果如下:

 

 

温度

温度也是在同一个div里面,温度的值在i标签中

 

 

那么xpath规则为:

//*[@id="around"]/div/ul/li/a/i/text()

效果如下:

 

 

三、完整代码

复制代码
import requests
from lxml import etree

url = 'http://www.weather.com.cn/weather1d/101010100.shtml#input'
with requests.get(url) as res:
    content = res.content
    html = etree.HTML(content)

location = html.xpath('//*[@id="around"]//a[@target="_blank"]/span/text()')
temperature = html.xpath('//*[@id="around"]/div/ul/li/a/i/text()')
data = dict(zip(location, temperature))
# print(data,len(data))

# 数据列表
data_list = []
for i in data:
    # 切割
    high,low = data[i].split('/')
    dic = {'location':i,'high':high,'low':low}
    data_list.append(dic)

print(data_list)
View Code
复制代码

执行输出:

[{'location': '香河', 'high': '36', 'low': '23°C'}, {'location': '涿州', 'high': '36', 'low': '25°C'}, {'location': '唐山', 'high': '34', 'low': '24°C'}, {'location': '沧州', 'high': '33', 'low': '26°C'}, {'location': '天津', 'high': '34', 'low': '27°C'}, {'location': '廊坊', 'high': '36', 'low': '24°C'}, {'location': '太原', 'high': '32', 'low': '23°C'}, {'location': '石家庄', 'high': '34', 'low': '26°C'}, {'location': '涿鹿', 'high': '32', 'low': '20°C'}, {'location': '张家口', 'high': '30', 'low': '17°C'}, {'location': '保定', 'high': '36', 'low': '24°C'}, {'location': '三河', 'high': '35', 'low': '23°C'}, {'location': '北京孔庙', 'high': '37', 'low': '23°C'}, {'location': '北京国子监', 'high': '37', 'low': '23°C'}, {'location': '中国地质博物馆', 'high': '37', 'low': '23°C'}, {'location': '月坛公园', 'high': '37', 'low': '22°C'}, {'location': '明城墙遗址公园', 'high': '37', 'low': '23°C'}, {'location': '北京市规划展览馆', 'high': '35', 'low': '24°C'}, {'location': '什刹海', 'high': '37', 'low': '22°C'}, {'location': '南锣鼓巷', 'high': '37', 'low': '23°C'}, {'location': '天坛公园', 'high': '35', 'low': '24°C'}, {'location': '北海公园', 'high': '35', 'low': '24°C'}, {'location': '景山公园', 'high': '35', 'low': '24°C'}, {'location': '北京海洋馆', 'high': '37', 'low': '23°C'}]
View Code

注意:这里2个列表转换为一个字典,使用了zip()函数。

 

本文参考链接:

https://github.com/jackzhenguo/python-small-examples/

 

posted @   肖祥  阅读(548)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2019-08-02 ubuntu 安装Jenkins
2018-08-02 python 全栈开发,Day96(Django REST framework 视图,django logging配置,django-debug-toolbar使用指南)
点击右上角即可分享
微信分享提示