Scrapy。从div中提取html而不包装父标记

时间:2013-03-25 18:03:12

标签: python html xpath css-selectors scrapy

我使用scrapy抓取网站。

我想提取某些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.,空格,我需要保留它们。

2 个答案:

答案 0 :(得分:2)

hxs = HtmlXPathSelector(response)
for text in hxs.select("//div[@class='short-description']/text()").extract(): 
    print text

答案 1 :(得分: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'