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

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

发布时间:2020-08-26 09:45:28编辑:admin阅读(1023)

[

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

...

]

二、分析页面

地区

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

5767c9dccabf88365b168aaa15c001b8.png

那么xpath规则为://*[@id="around"]//a[@target="_blank"]/span/text()

效果如下:

bbf6e1ab0783615689bfa6f626575c60.png

温度

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

9ee5db99363188dd7bbfc079ef6efc15.png

那么xpath规则为://*[@id="around"]/div/ul/li/a/i/text()

效果如下:

628eba5081d141b165daaed824b31103.png

三、完整代码

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()函数。

本文参考链接:

关键字:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值