admin管理员组

文章数量:1619183

文章目录

  • 第一步:将网页另存到本地
  • 第二步:找到所需要提取内容的Xpath
  • 第三步:使用lxml.etree方法进行解析和提取

欧盟委员会(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中简单编辑,就得到了下表

本文标签: 关键词快速网页etreelxml