2016-05-02 26 views
2
で始まる要素のテキストを取得します

このhtmlスニペットからテキスト "< 1時間"を取得しようとしています。Scrapy xpathは<

<div class="details_wrapper"> 
<div class="detail"> 
    <b>Recommended length of visit:</b> 
    <1 hour 
</div> 
<div class="detail"> 
    <b>Fee:</b> 
    No 
</div> 
</div> 

これは、私が使用していますXPath式である:

visit_length = response.xpath(
    "//div[@class='details_wrapper']/" 
    "div[@class='detail']/b[contains(text(), " 
    "'Recommended length of visit:')]/parent::div/text()" 
).extract() 

しかし、テキストを取得することができません。私はこれが私が必要とするテキストの "<"によると思う、それはhtmlタグと見なされている。テキスト "< 1時間"をどうやって掻くことができますか?

答えて

2

Scrapyは、ボンネットの下にlxmlを使用していることを考えると、それはlxmlは、テキストノードの一つにXML特殊文字<が含まれているHTMLのこの種の、どのように処理するかを検査する価値があります上記のデモで

>>> from lxml import html 
>>> raw = '''<div class="details_wrapper"> 
... <div class="detail"> 
...  <b>Recommended length of visit:</b> 
...  <1 hour 
... </div> 
... <div class="detail"> 
...  <b>Fee:</b> 
...  No 
... </div> 
... </div>''' 
... 
>>> root = html.fromstring(raw) 
>>> print html.tostring(root) 
<div class="details_wrapper"> 
<div class="detail"> 
    <b>Recommended length of visit:</b> 

<div class="detail"> 
    <b>Fee:</b> 
    No 
</div> 
</div></div> 

お知らせあなたが疑うように、テキストノード'<1 hour'は、要素ソースrootから完全になくなっています。それは、このHTMLの場合の取り扱いで、より合理的であるため、回避策として、(あなたがScrapy応答からsoupを作成するためのresponse.body_as_unicode()を渡すことができます)BeautifulSoupを使用して検討してください。

>>> from bs4 import BeautifulSoup 
>>> soup = BeautifulSoup(raw, "html.parser") 
>>> print soup.prettify() 
<div class="details_wrapper"> 
<div class="detail"> 
    <b> 
    Recommended length of visit: 
    </b> 
    &lt;1 hour 
</div> 
<div class="detail"> 
    <b> 
    Fee: 
    </b> 
    No 
</div> 
</div> 

BSを使用してターゲットテキストノードは、次のように行うことができます検索:すでにscrapyパーサParselに報告したように

>>> soup.find('b', text='Recommended length of visit:').next_sibling 
u'\n <1 hour\n' 
+0

ありがとう:それはそこに言うように、あなたのクモは、このようなものでなければなりません

は、解決策は、セレクタにtype='xml'引数を渡すことであろう!それは働いた:) –

1

これはlxml問題であり、ここでthe issueをご確認ください。

from scrapy import Selector 
... 
... 
    def your_parse_method(self, response): 
     sel = Selector(text=response.body_as_unicode(), type='xml') 
     # now use "sel" instead of response for getting xpath info 
     ... 
     visit_length = sel.xpath("//div[@class='details_wrapper']/" 
      "div[@class='detail']/b[contains(text(), " 
      "'Recommended length of visit:')]/parent::div/text()").extract() 
+0

十分に閉じる!ありがとう!しかし、出力は1時間未満ではなく1時間です。 –

+0

ええ、それらの文字を削除します – eLRuLL

関連する問題