使用 Node.js 实现通用网络爬虫

Implementing a Generic Web Scraper using Node.js

我想使用 Node.js 实现一个尽可能通用的基本网络抓取工具。我希望应用程序能够解析和 return 来自任何 HTML 的文本,忽略任何 Markup/CSS/Script,而不必知道要提前解析的 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());
    }
});

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

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);

希望对您有所帮助!

我相信 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);