2016-12-27 130 views
1

我認爲我使用的是Scrapy錯誤,但我試圖使用xpath從頁面上的H2中僅選擇文本並去掉內部標籤。嵌套元素的Scrapy xpath

例如。

<h2>Welcome to my <a href="#">page</a></h2> 
<h2>Welcome to my Page</h2> 

我一直在使用//h2//text()嘗試,但它會產生這樣的

item["h2s"] = response.xpath('//h2//text()').extract() 

['Welcome to my', 
'page', 
'Welcome to my Page'] 

我已經試過組合的數量,只是一個陣列似乎並不像我想下面

獲取數組
['Welcome to my page', 
'Welcome to my Page'] 

回答

1

你可能會加入所有文本節點爲每個h2

In [1]: [''.join(h2.xpath(".//text()").extract()) for h2 in response.xpath("//h2")] 
Out[1]: [u'Welcome to my page', u'Welcome to my Page'] 

本主題也頗爲相關:

+1

好極了,只是試了一下,完美工作:)感謝。在Scrapy中做一些相對簡單的事情看起來相當複雜。 –