3

私はスクレイピーを使ってウェブサイトをクロールしています。

特定のdivの内容を抽出したい。

<div class="short-description">
{some mess with text, <br>, other html tags, etc}
</div>

loader.add_xpath('short_description', "//div[@class='short-description']/div")

そのコードによって、必要なものを取得できますが、結果にはラッピング html が含まれます ( <div class="short-description">...</div>)

その親htmlタグを取り除く方法は?

。text()、node() のようなセレクターは役に立ちません。私の div には<br>, <p>, other divs, etc.、空白が含まれており、それらを保持する必要があるからです。

4

2 に答える 2

2
hxs = HtmlXPathSelector(response)
for text in hxs.select("//div[@class='short-description']/text()").extract(): 
    print text
于 2013-03-26T01:35:55.603 に答える
2

node()と組み合わせてみてくださいJoin()

loader.get_xpath('//div[@class="short-description"]/node()', Join())

結果は次のようになります。

>>> from scrapy.contrib.loader import XPathItemLoader
>>> from scrapy.contrib.loader.processor import Join
>>> from scrapy.http import HtmlResponse
>>>
>>> body = """
...     <html>
...         <div class="short-description">
...             {some mess with text, <br>, other html tags, etc}
...             <div>
...                 <p>{some mess with text, <br>, other html tags, etc}</p>
...             </div>
...             <p>{some mess with text, <br>, other html tags, etc}</p>
...         </div>
...     </html>
... """
>>> response = HtmlResponse(url='http://example.com/', body=body)
>>>
>>> loader = XPathItemLoader(response=response)
>>>
>>> print loader.get_xpath('//div[@class="short-description"]/node()', Join())

            {some mess with text,  <br> , other html tags, etc}
             <div>
                <p>{some mess with text, <br>, other html tags, etc}</p>
            </div>
             <p>{some mess with text, <br>, other html tags, etc}</p>
>>>
>>> loader.get_xpath('//div[@class="short-description"]/node()', Join())
u'\n            {some mess with text,  <br> , other html tags, etc}\n
   <div>\n         <p>{some mess with text, <br>, other html tags, etc}</p>\n
   </div> \n     <p>{some mess with text, <br>, other html tags, etc}</p> \n'
于 2013-03-26T03:33:00.660 に答える