【问题标题】:Extracting p within h1 with Python/Scrapy使用 Python/Scrapy 在 h1 中提取 p
【发布时间】:2017-11-05 11:30:41
【问题描述】:

我正在使用 Scrapy 从网站上提取一些关于音乐会的数据。我正在使用的至少一个网站使用(错误地,根据 W3C - Is it valid to have paragraph elements inside of a heading tag in HTML5 (P inside H1)?)在 h1 元素中使用 p 元素。尽管如此,我仍需要提取 p 元素中的文本,但不知道如何提取。

我已阅读文档并查看了示例用途,但对 Scrapy 来说相对较新。我了解该解决方案与将 Selector 类型设置为“xml”而不是“html”以识别任何 XML 树有关,但是对于我的一生,我无法弄清楚在这种情况下如何或在哪里执行此操作。

例如,一个网站具有以下 HTML:

<h1 class="performance-title">
<p>Bernard Haitink conducts Brahms and&nbsp;Dvořák featuring pianist     Emanuel Ax
</p>
</h1>

我创建了一个名为 Concert() 的项目,其值名为“title”。在我的项目加载器中,我使用:

def parse_item(self, response):       
    thisconcert = ItemLoader(item=Concert(), response=response)
    thisconcert.add_xpath('title','//h1[@class="performance-title"]/p/text()')

    return thisconcert.load_item()

这会在 item['title'] 中返回一个 unicode 列表,其中不包含 p 元素内的文本,例如:

['\n                 ', '\n                 ', '\n                ']

我明白为什么,但我不知道如何解决它。我也尝试过:

from scrapy import Selector

def parse_item(self, response):  

    s = Selector(text=' '.join(response.xpath('.//section[@id="performers"]/text()').extract()), type='xml')

我在这里做错了什么,如何解析包含此问题的 HTML(h1 中的 p)?

我在Behavior of the scrapy xpath selector on h1-h6 tags 上引用了有关此特定问题的信息,但它没有提供可应用于蜘蛛的完整解决方案,只是会话中使用给定文本字符串的示例。

【问题讨论】:

  • 试试这个 xpath: "//h1[@class="performance-title"]/text()" 除了在 chrome 开发工具中尝试(控制台)$x'='/ /h1[@class="performance-title"]/text()'
  • 谢谢。我刚才试过了,仍然得到一组类似的空字符串。
  • 把链接发给我!
  • bso.org/Performance/Detail/88671 感谢您的帮助。

标签: python html scrapy lxml


【解决方案1】:

那真是莫名其妙。坦率地说,我仍然不明白为什么会这样。发现应该包含在&lt;h1&gt; 标记中的&lt;p&gt; 标记并非如此。网站的 Curl 显示形式为 &lt;h1&gt;&lt;p&gt; &lt;/p&gt;&lt;/h1&gt;,而从网站获得的 响应 显示为:

<h1 class="performance-title">\n</h1>
<p>Bernard Haitink conducts Brahms and\xa0Dvo\u0159\xe1k featuring\npianist Emanuel Ax
</p>

正如我所提到的,我确实有疑问,但没有具体的。无论如何,用于获取 &lt;p&gt; 标记内的文本的 xpath 因此是:

response.xpath('//h1[@class="performance-title"]/following-sibling::p/text()').extract()

这是通过使用&lt;h1 class="performance-title"&gt; 作为地标并找到其兄弟&lt;p&gt; 标签

【讨论】:

  • 当然,很高兴为您提供帮助。
【解决方案2】:
//*[@id="content"]/section/article/section[2]/h1/p/text()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 2015-06-11
相关资源
最近更新 更多