首页 > 解决方案 > Scrapy :仅整个页面的 RENDERED TEXT(人眼所见)

问题描述

我如何抓取相当于:在浏览器中突出显示整个页面(即不是页面源),在记事本中复制/粘贴(即没有超链接,只有文本)

    class TextOnlySpider(scrapy.Spider): 

    name = "onepage"

    allowed_domains = ["en.wikipedia.org"]
    start_urls = ['https://en.wikipedia.org/wiki/Congee']

    def start_requests(self):
        urls = [
            'https://en.wikipedia.org/wiki/Congee'
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        # Below line gives HTML/javascript, etc.
        # I only want TEXT equaivalent. i.e Same text content that one gets, by copying in browser and pasting in Notepad/vim
        bodyText = '\n'.join(response.xpath('//text()').extract())
        yield{
            'text': bodyText, #TODO only get TEXT equivalent of rendered page (text seen by human eyes)
            'title': response.url, #TODO change to title
            'id':response.url,
        }

我想要人类阅读的文本,而不是这个答案中的页面源:
Scrapy Body Text Only

原因:

我将获取文本表示形式、页面 url 并在 elasticsearch 中对其进行索引,使其成为站点搜索解决方案。索引时我不想要凌乱的 html/js 代码。

标签: scrapy

解决方案


模块 html2text 可以在删除标签的同时将 html 转换为纯文本:

import html2text
converter = html2text.HTML2Text()
bodyText = converter.handle(response.text)

如果您还想获取呈现的文本,则需要像 Splash 这样的无头浏览器来首先呈现页面。


推荐阅读