【问题标题】:Implementing a Generic Web Scraper using Node.js使用 Node.js 实现通用 Web Scraper
【发布时间】:2019-06-09 15:33:39
【问题描述】:

我想使用尽可能通用的 Node.js 实现一个基本的网络爬虫。我希望应用程序能够解析和返回来自任何 HTML 的文本,忽略任何标记/CSS/脚本,而不必提前知道要解析的 HTML 的结构。

我一直在考虑使用这个库:

https://github.com/cheeriojs/cheerio

使用下面的代码,我可以从 body 标记中提取文本,但这也包含 CSS 和 JavaScript。仅提取文本而不包含 CSS/JavaScript 的最佳方法是什么?

代码:

 var request = require('request');
var cheerio = require('cheerio');
var URL = require('url-parse');

var pageToVisit = "http://www.arstechnica.com";
console.log("Visiting page " + pageToVisit);
request(pageToVisit, function (error, response, body) {
    if (error) {
        console.log("Error: " + error);
    }
    // Check status code (200 is HTTP OK)
    console.log("Status code: " + response.statusCode);
    if (response.statusCode === 200) {
        // Parse the document body
        var $ = cheerio.load(body);
        console.log($('body').text());
    }
});

【问题讨论】:

  • 阅读库的文档我看到它提供了一个.remove() 方法。也许你可以用它来删除不需要的元素。
  • 看起来像$('script,style').remove()

标签: node.js web-scraping html-parsing cheerio


【解决方案1】:

我相信 cherio.load(body) 会给你一个 DOM。如果是这样,您可以使用 innerText 类似这样的东西:

    // Parse the document body
    var $ = cheerio.load(body);
    console.log($('body').innerText);

如果 cherio 为您提供 HTML,您可以使用 JSDOM 将其转换为 DOM,如下所示:

    // Parse the document body
    const jsdom = require(jsdom);
    const dom = jsdom.JSDOM(cheerio.load(body),{"url": pageToVisit}).window.document.body;
    console.log(dom.innerText);

【讨论】:

    【解决方案2】:

    查看我看到的其他答案,您可以使用正则表达式来做到这一点,这是一个示例:

    let scriptRegex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
    let styleRegex = /((<style>)|(<style type=.+))((\s+)|(\S+)|(\r+)|(\n+))(.+)((\s+)|(\S+)|(\r+)|(\n+))(<\/style>)/g;
    
    // An example html content
    const str = `
    my cool html content
    <style>
    ...
    </style>
    my cool html content
    <style type="text/css">
    ...
    </style>
    my cool html content
    <script> 
    ... 
    </script>
    my cool html content`;
    
    // Strip the tags from the html
    let result = str.replace(scriptRegex, '');
    result = result.replace(styleRegex, '');
    
    // There you go :)
    console.log('Substitution result: ', result);
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      相关资源
      最近更新 更多