【问题标题】:Scrapy, Xpath, extracting h3 content?Scrapy,Xpath,提取h3内容?
【发布时间】:2020-10-28 00:08:13
【问题描述】:

我需要在 h3 class AIRFRAME /h3 但在 h3 class ENGINES /h3 之前提取所有内容:

我需要提取的内容:

“投入使用:2010 年 12 月 自新开始以来的总时间:3,580 小时”等。

HTML code photo - not sure how to embed it directly instead of having a link

以下是我尝试过的,但它没有返回任何内容。我是 Scrapy 和一般编程的新手,所以我希望能得到一些帮助。我试过搜索其他帖子和谷歌一般没有任何运气。

input = response.xpath("//div[@class='large-6 cell selectorgadget_rejected']/h3/text()").extract()

输出 = []

【问题讨论】:

  • 从不将代码包含为图像。始终将其作为文本复制到 code 部分中,否则无法复制尝试,并且对 SO 毫无价值。
  • 提示:检查@class 属性的值是否包含换行符。
  • 谢谢。这是我的第一篇文章,所以我会牢记这一点。

标签: html python-3.x xpath web-scraping scrapy


【解决方案1】:

您正在使用的代码引用了另一个没有您提到的文本的类。

input = response.xpath("//div[@class='large-6 cell selectorgadget_rejected']/h3/text()").extract()

图中班级的名字是large-6 cell selectorgadget_selected而不是large-6 cell selectorgadget_rejected

另外,如果你使用.../h3/text(),你会刮掉H3标签内的文字。 据我了解,您想要 H3 之后的文本,在 <div> 之间。所以尝试这样的事情:

input = response.xpath("//div[@class='large-6 cell selectorgadget_selected']/text()").extract()

【讨论】:

  • 谢谢。使用上面的代码作为参考(我做了一点改动),我能够在<H3> 标记之后获得内容的输出。代码是:response.xpath("//div[@class='large-6 cell']/text()").extract() 有 4 个不同的<H3> 标签,我需要从中获取信息,AIRFRAME 就是其中之一。这 4 个标签是 large-6 cell 类的一部分,因此我在同一输出中获得了所有 4 个标签的结果。我将如何更改我的代码以使输出仅用于 AIRFRAME?
  • 嗨@Arty,如果没有看到实际的html,这很难回答。您可以在 XPath 中尝试类似的操作://div[@class='large-6 cell']/h3[contains(text(), "AIRFRAME")]/parent::div/text()。它只会找到包含引号 " " 内的文本的 H3,并将返回给父 <div> 的文本。 - 如果我的回答解决了您的问题,请点击对勾接受。
【解决方案2】:

要完成@renatodvc 的回答,您可以添加normalize-space 函数来忽略空白节点。

//div[@class='large-6 cell selectorgadget_selected']/text()[normalize-space()]

或者直接在元素上使用函数:

normalize-space(//div[@class='large-6 cell selectorgadget_selected'])

输出:

AIRFRAME " Entry Into Service: December 2010" " Total Time Since New: 3,58@ Hours" " Total Landings Since New: 1,173" " (as of September 2019)" " Program Coverage: Enrolled on Smart Parts Plus" " Maintenance Tracking: CAMP "

然后,要提取值,您可以使用正则表达式:

import re
text = 'AIRFRAME " Entry Into Service: December 2010" " Total Time Since New: 3,58@ Hours" " Total Landings Since New: 1,173" " (as of September 2019)" " Program Coverage: Enrolled on Smart Parts Plus" " Maintenance Tracking: CAMP "'
data = [el.strip() for el in re.findall(':(.+?)\"', text, re.IGNORECASE)]
print(data)

输出:

['December 2010', '3,58@ Hours', '1,173', 'Enrolled on Smart Parts Plus', 'CAMP']

【讨论】:

  • 谢谢! normalize-space 函数似乎不起作用。我尝试了以下代码response.xpath("//div[@class='large-6 cell']/text()")[normalize-space()].extract() 并得到了以下错误name 'normalize' is not defined
  • 您的表达中有错字。应该是:response.xpath("//div[@class='large-6 cell selectorgadget_selected']/text()[normalize-space()]").get()
猜你喜欢
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多