使用lxml.etree配合Xpath快速爬取100项网页关键词

本文介绍了如何使用Python的lxml库通过XPath从网页中提取特定内容,以欧盟发布的100项创新技术为例,详细阐述了从保存网页到定位Xpath,再到解析和提取数据的完整过程,帮助读者掌握自动化数据提取技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


欧盟委员会(EUROPEAN COMMISSION)发布《面向未来的100项重大创新突破》(100 Radical Innovation Breakthroughs for the future)报告,我们在微信公众号文章中可以看到原文 面向未来的100项颠覆性技术创新。现在我有一个需求,就是把这100项技术提取出来,如果手动提取的话,就会比较累,那么我们能不能使用python来进行提取呢?答案是肯定的,只需要使用lxml模块中的etree方法,使用Xpath语法就可以完成这个功能了。

第一步:将网页另存到本地

我们可以在浏览器中依次点击右键-另存为,将这个网页保存到本地,在这里,我把这个文件命名为了"toptech.html"
在这里插入图片描述

第二步:找到所需要提取内容的Xpath

这个如果手写的话需要学习Xpath语法,不过我们的浏览器已经帮我们做好了解析的工作,我们只需要直接右键就可以得到Xpath了,如下图所示:
在这里插入图片描述
这个步骤要在开发者工具里面执行,Chrome浏览器中的快捷键是“ctr+shift+J”,然后使用左上角的选择工具(箭头图表),左键选择需要找到的对象,然后在右边右键CopyXpath,就可以得到所需要的Xpath了,我找了一些元素,他们的Xpath如下所示:

//*[@id="js_content"]/section[3]/section/section[4]/section/section/section/p/span/strong

//*[@id="js_content"]/section[3]/section/section[3]/section/section/section/p/span/strong

//*[@id="js_content"]/section[3]/section/section[7]/section/section/section/p/span/strong

//*@id="js_content"]/section[3]/section/section[106]/section/section/section/section/p/span/strong

不难找出规律,得到通用的表达式:

//*[@id="js_content"]/section[3]/section/section[*]/section/section/section/p/span/strong

//*[@id="js_content"]/section[3]/section/section[*]/section/section/section/section/p/span/strong

第三步:使用lxml.etree方法进行解析和提取

这里我参考了Python利用requests和xpath爬取网页内容过程 这篇博客,然后编写了以下简单的代码:

from lxml import etree
html = etree.parse('./toptech.html', etree.HTMLParser())
results = html.xpath('//*[@id="js_content"]/section[3]/section/section[*]/section/section/section/p/span/strong')
for result in results:	
	print(result.text)
results = html.xpath('//*[@id="js_content"]/section[3]/section/section[*]/section/section/section/section/p/span/strong')
for result in results:	
	print(result.text)

运行之后,我们就可以把这100个技术的名字全部打印出来啦~开心!

在这里插入图片描述
在excel中简单编辑,就得到了下表
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值