我正在使用Scrapy從網站中提取有關音樂會的一些數據。至少有一個我正在使用的網站(錯誤地根據W3C - Is it valid to have paragraph elements inside of a heading tag in HTML5 (P inside H1)?)使用h1元素中的p元素。我需要提取p元素中的文本,但無法弄清楚。用Python/Scrapy在h1內提取p-1
我已閱讀文檔並查看了示例用途,但是對於Scrapy來說,這是相對較新的。我知道解決方案與將Selector類型設置爲「xml」而不是「html」以便識別任何XML樹有關,但對於我的生活,我無法弄清楚在這種情況下如何或在哪裏做。
例如,一個網站具有以下HTML:
<h1 class="performance-title">
<p>Bernard Haitink conducts Brahms and Dvořák featuring pianist Emanuel Ax
</p>
</h1>
我做了一個項目叫做演唱會(),有一個名爲「標題」值。在我的項目裝載機,我使用:
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()
這將返回,項[「標題」],不包括p元素中的文本unicode的列表,如:
['\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')
我在做什麼錯在這裏,我怎麼可以解析包含此問題(H1內P)HTML?
我已經提到了關於這個具體問題上的信息,在Behavior of the scrapy xpath selector on h1-h6 tags,但它並沒有提供一個會話中使用給定文本字符串,可以應用到蜘蛛的完整解決方案,只是一個例子。
給它這個XPath一試:「除了在chrome開發工具(控制檯)中嘗試使用h1 [@ class =「performance-title」]/text()$ x'='// h1 [@ class =「performance-title」]/text()' – mtt2p
謝謝。我剛剛嘗試過,仍然得到一組類似的空字符串。 – NFB
給我鏈接! – mtt2p