Node.js 如何抓取所有内部url';使用爬虫的网站的安全性?
我想使用node.js中的爬虫来抓取网站中的所有链接(内部链接),并获取每个页面的标题,我在npm上看到了这个插件,如果我查看文档,有以下示例:Node.js 如何抓取所有内部url';使用爬虫的网站的安全性?,node.js,web-crawler,Node.js,Web Crawler,我想使用node.js中的爬虫来抓取网站中的所有链接(内部链接),并获取每个页面的标题,我在npm上看到了这个插件,如果我查看文档,有以下示例: var Crawler = require("crawler"); var c = new Crawler({ maxConnections : 10, // This will be called for each crawled page callback : function (error, res, done) {
var Crawler = require("crawler");
var c = new Crawler({
maxConnections : 10,
// This will be called for each crawled page
callback : function (error, res, done) {
if(error){
console.log(error);
}else{
var $ = res.$;
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
console.log($("title").text());
}
done();
}
});
// Queue just one URL, with default callback
c.queue('http://balenol.com');
但我真正想要的是抓取网站中的所有内部URL,这些URL是内置在这个插件中的,还是需要单独编写?我在插件中看不到任何访问站点中所有链接的选项,这可能吗?下面的代码片段会对找到的每个URL中的所有URL进行爬网
const Crawler = require("crawler");
let obselete = []; // Array of what was crawled already
let c = new Crawler();
function crawlAllUrls(url) {
console.log(`Crawling ${url}`);
c.queue({
uri: url,
callback: function (err, res, done) {
if (err) throw err;
let $ = res.$;
try {
let urls = $("a");
Object.keys(urls).forEach((item) => {
if (urls[item].type === 'tag') {
let href = urls[item].attribs.href;
if (href && !obselete.includes(href)) {
href = href.trim();
obselete.push(href);
// Slow down the
setTimeout(function() {
href.startsWith('http') ? crawlAllUrls(href) : crawlAllUrls(`${url}${href}`) // The latter might need extra code to test if its the same site and it is a full domain with no URI
}, 5000)
}
}
});
} catch (e) {
console.error(`Encountered an error crawling ${url}. Aborting crawl.`);
done()
}
done();
}
})
}
crawlAllUrls('https://github.com/evyatarmeged/');
在上面的代码中,只需更改以下内容即可获得网站的内部链接 从 到
工作得很好,但值得注意的是,此脚本将抓取页面中引用的所有外部URL,以便根据需要编辑:)
href.startsWith('http') ? crawlAllUrls(href) : crawlAllUrls(`${url}${href}`)
href.startsWith(url) ? crawlAllUrls(href) : crawlAllUrls(`${url}${href}`)