进一步,本文使用了 xpath 来获取特定标签所储存的信息。XPath,全称 XML Path Language,即 XML 路径语言。XPath 最初设计是用来搜寻 XML 文档的,但是也同样适用于 HTML 文档的搜索。XPath 的选择功能十分强大,不但提供了非常简洁明了的路径选择表达式,而且还提供了超过 100 个内建函数用于字符串、数值、时间的匹配,以及节点、序列的处理等。甚至,我们可以认为几乎所有定位的节点都可以用 XPath
来选择。
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'} #构造头文件,模拟浏览器。 for page in range(1,max_page+1): #获取网页源代码 print('crawling the page is {}'.format(page)) url= f'http://guba.eastmoney.com/list,zssh000001,f_{page}.html' response = requests.get(url, headers=headers)
然后,通过 xpath 解析网页源代码,我们就可以获取需要信息。
在谷歌浏览器内按 F12 进入开发者模型,审查我们所需要的元素,如下图:
可以看出,所有的标题和时间都保存在属性为 articleh normal_post 的 div 标签下,因此我们可以构造如下代码进行爬取。当然,以上过程也可以借助 XPath Helper 工具大大简化,
title = root.xpath("//div[contains(@class,'articleh normal_post')]//span[@class='l3 a3']//a//text()") time = root.xpath("//div[contains(@class,'articleh normal_post')]//span[@class='l5 a5']//text()")
完整代码如下:
max_page = 20#最大爬取页面 all_title = [] #爬取的标题存储列表 all_time = [] #爬取的发表时间储存列表 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'} #构造头文件,模拟浏览器。 for page in range(1,max_page+1): #获取网页源代码 print('crawling the page is {}'.format(page)) url= f'http://guba.eastmoney.com/list,zssh000001,f_{page}.html' response = requests.get(url, headers=headers) #解析网页源代码 root = etree.HTML(response.text) title = root.xpath("//div[contains(@class,'articleh normal_post')]//span[@class='l3 a3']//a//text()") time = root.xpath("//div[contains(@class,'articleh normal_post')]//span[@class='l5 a5']//text()") all_title += title #保存到总数组上 all_time += time