2016-09-26 1 views
0

이 html의 itemprop = "ingredients"안에있는 텍스트를 모두 추출하려고합니다.Scrap - v2.0에서 Xpath 중첩 된 텍스트 연결하기

나는 this answer을보고 정확히 원하는 부분이지만 요소가 지정되어 있고 텍스트가 내부에 중첩되어 있지 않습니다.

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

내가 필요로하는 목록으로 다시 텍스트를 얻을 것입니다,이 목록의 첫 번째 요소는 여기에 "성분 삽입 공간의 시작이 될 가입하거나 뭔가됩니다

은 HTML입니다 Rest of 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'] 

을하지만 난이 원하는 :

나는과의 긴밀한 가지고

['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

I 서수> (127)가없는 (유명한 오류 : UnicodeEncodeError 'ASCII'코덱 위치 (16)에 문자 U '\의 XAE'를 인코딩하지 수 범위 내에 있지 순서 (128)) –