Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrapy: Extract commented (hidden) content

Tags:

scrapy

How can I extract content from within commented tags with scrappy ?

For instance, how to extract "Yellow" in the following example:

<div class="fruit">
    <div class="infos">
        <h2 class="Name">Banana</h2>
        <span class="edible">Edible: Yes</span>
    </div>
    <!--
    <p class="color">Yellow</p>
    -->
</div>
like image 663
Mathieu Avatar asked Jan 11 '23 04:01

Mathieu


1 Answers

You can use an XPath expression like //comment() to get the comment content, and then parse that content after having stripped the comment tags.

Example scrapy shell session:

paul@wheezy:~$ scrapy shell 
...
In [1]: doc = """<div class="fruit">
   ...:     <div class="infos">
   ...:         <h2 class="Name">Banana</h2>
   ...:         <span class="edible">Edible: Yes</span>
   ...:     </div>
   ...:     <!--
   ...:     <p class="color">Yellow</p>
   ...:     -->
   ...: </div>"""

In [2]: from scrapy.selector import Selector

In [4]: selector = Selector(text=doc, type="html")

In [5]: import re

In [6]: regex = re.compile(r'<!--(.*)-->', re.DOTALL)

In [7]: selector.xpath('//comment()').re(regex)
Out[7]: [u'\n    <p class="color">Yellow</p>\n    ']

In [8]: comment = selector.xpath('//comment()').re(regex)[0]

In [9]: commentsel = Selector(text=comment, type="html")

In [10]: commentsel.css('p.color')
Out[10]: [<Selector xpath=u"descendant-or-self::p[@class and contains(concat(' ', normalize-space(@class), ' '), ' color ')]" data=u'<p class="color">Yellow</p>'>]

In [11]: commentsel.css('p.color').extract()
Out[11]: [u'<p class="color">Yellow</p>']

In [12]: commentsel.css('p.color::text').extract()
Out[12]: [u'Yellow']
like image 118
paul trmbrth Avatar answered Jan 14 '23 16:01

paul trmbrth