2016-12-27 128 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中做一些相对简单的事情看起来相当复杂。 –