Reputation: 369
I use scrapy to crawl a website.
I want to extract contents of certain 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")
By that code I get what I need but result includes wrapping html (<div class="short-description">...</div>
)
How to get rid of that parent html tag?
Note. Selector like text(), node() cannot help me, because my div contains <br>, <p>, other divs, etc.
, whitespaces, and I need to keep them.
Upvotes: 3
Views: 3983
Reputation: 8202
Try node()
in combination with Join()
:
loader.get_xpath('//div[@class="short-description"]/node()', Join())
and the results look something like:
>>> 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'
Upvotes: 2
Reputation: 98108
hxs = HtmlXPathSelector(response)
for text in hxs.select("//div[@class='short-description']/text()").extract():
print text
Upvotes: 1