2016-09-26 30 views
0

我想提取这个网站是在itemprop =“配料”中的所有文本。在Scrapy串联Xpath的嵌套文本 - 2.0

我看到this answer,这是我想要的东西,但也有指定的元素,和我的文字是不是嵌套。

这是HTML:

<li itemprop="ingredients">Beginning of ingredient 
    <a href="some-link" data-ct-category="Other" 
    data-ct-action="Site Search" 
    data-ct-information="Recipe Search - Hellmann's® or Best Foods® Real Mayonnaise" 
    data-ct-attr="some_attr">Rest of Ingredient</a> 
</li> 
<li itemprop="ingredients">Another ingredient</li> 
<li itemprop="ingredients">Another ingredient</li> 
<li itemprop="ingredients">Another ingredient</li> 
<li itemprop="ingredients">Another ingredient</li> 
<li itemprop="ingredients">Another ingredient</li> 

我需要的是让背课文,作为一个列表,这个列表中的第一个元素将是“的成分插入空间开头这里,参加什么其余的成分“,其他元素将是”另一种成分“。

我接近有:

for row in response.xpath('//*[@itemprop="ingredients"]/descendant-or-self::*/text()'): 
...  print row.extract() 
... 
Beginning of ingredient 
Rest of Ingredient 

    Another ingredient 
    Another ingredient 
    Another ingredient 
    Another ingredient 
    Another ingredient 

所以,当我把它放在一个列表使用extract_first()上的每一行,我得到这个:

['Beginning of ingredient', "Rest of Ingredient", 'Another ingredient', 'Another ingredient', 'Another ingredient', 'Another ingredient', 'Another ingredient'] 

但我想这一点:

['Beginning of ingredient Rest of Ingredient', 'Another ingredient', 'Another ingredient', 'Another ingredient', 'Another ingredient', 'Another ingredient'] 

回答

0

您已经关闭,每过一个li元素,然后调用上下文相关的descendant-or-self

In [1]: [" ".join(map(unicode.strip, item.xpath("descendant-or-self::text()").extract())) 
     for item in response.xpath('//li[@itemprop="ingredients"]')] 
Out[1]: 
[u'Beginning of ingredient Rest of Ingredient ', 
u'Another ingredient', 
u'Another ingredient', 
u'Another ingredient', 
u'Another ingredient', 
u'Another ingredient'] 
+0

我不能有序> 127(著名错误:UnicodeEncodeError: 'ASCII' 编解码器不能在位置16编码字符U '\ XAE':序数不在范围内(128)) –