【问题标题】:how to crawl all the internal url's of a website using crawler?如何使用爬虫抓取网站的所有内部网址?
【发布时间】:2018-05-03 11:36:26
【问题描述】:

我想在 node.js 中使用爬虫来爬取网站中的所有链接(内部链接)并获取每个页面的标题,我在 npm crawler 上看到了这个插件,如果我查看文档有下面的例子:

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

但我真正想要的是抓取网站中的所有内部网址,并且是内置在这个插件中还是需要单独编写?我在插件中没有看到任何选项来访问网站中的所有链接,这可能吗?

【问题讨论】:

    标签: node.js web-crawler


    【解决方案1】:

    下面的 sn-p 爬取它找到的每个 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
    • 随意编辑 :)
    【解决方案2】:

    在上面的代码中,只需更改以下内容即可获取网站的内部链接...

    来自

    href.startsWith('http') ? crawlAllUrls(href) : crawlAllUrls(`${url}${href}`)
    

    href.startsWith(url) ? crawlAllUrls(href) : crawlAllUrls(`${url}${href}`)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      相关资源
      最近更新 更多