2016-09-26 4 views
0

このhtmlのitemprop = "ingredients"の中にあるすべてのテキストを抽出しようとしています。Scrap - v2.0でXpathネストされたテキストを連結する

私は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> 

私は必要なものが戻ってリストとしてテキストを取得することであり、このリストの最初の要素は「ここ成分挿入空間の始まり、参加か何かだろう「残りの成分」、およびその他の成分は「別の成分」となる。

私はで親しま:

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

しかし、私はこれ欲しい::私は、各行に)(extract_first使用して、リストに入れたときので、私はこれを取得

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 

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

答えて

0

あなたは閉じており、liの要素をすべて取得してから、コンテキスト固有のdescendant-or-self私は> 127序を持つことができません

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

:(:UnicodeEncodeErrorを:有名エラー 'アスキー' コーデックが文字をエンコードすることはできませんuが16位に 'XAEを\':序ない範囲(128)で) –

関連する問題