Scrapy:提取评论(隐藏)内容

标签 scrapy

如何从带有scrapy的注释标签中提取内容?

例如,如何在以下示例中提取“黄色”:

<div class="fruit">
    <div class="infos">
        <h2 class="Name">Banana</h2>
        <span class="edible">Edible: Yes</span>
    </div>
    <!--
    <p class="color">Yellow</p>
    -->
</div>

最佳答案

您可以使用 XPath 表达式,如 //comment()获取评论内容,然后在剥离评论标签后解析该内容。

示例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']

关于Scrapy:提取评论(隐藏)内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21830812/

相关文章:

python - 在 Linux Ubuntu 上无法打开 Scrapy

python - 我怎样才能使 start_url 在 scrapy 中从消息队列中使用?

javascript - 如何绕过 Scrapy 中的 cloudflare bot/ddos 保护?

python - Tripadvisor 上的 Scrapy、爬行评论 : extract more hotel and user information

scrapy - 如何在 scrappy 中手动执行 Request 对象?

python - 同时抓取太多链接

python - 如何使用 Scrapy 循环抓取相同的 url

python - Scrapy 广泛抓取 - 在广泛抓取期间仅允许内部链接,allowed_domains 的域太多

python - 在 Chrome headless 模式下使用 Python 中的 Selenium 进行 Scrapyng AngularJS

python - 使用 scrapy 进行 CPU 密集型解析