gpt4 book ai didi

node.js - 使用 Node.js 实现通用 Web Scraper

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:03 26 4
gpt4 key购买 nike

我想使用 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());
}
});

最佳答案

查看其他答案,我发现您可以使用正则表达式来执行此操作,这是一个示例:

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

希望对你有帮助!

关于node.js - 使用 Node.js 实现通用 Web Scraper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com