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

时间:2022-07-24
本文章向大家介绍爬取天气数据并解析温度值,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、概述

获取北京周边城区的天气数据,链接如下: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)

执行输出:

[{'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'}]

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

本文参考链接:

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