【问题标题】:How to print html source to console with phantom-crawler如何使用 phantom-crawler 将 html 源打印到控制台
【发布时间】:2016-03-27 14:10:13
【问题描述】:

我刚刚下载并安装了 nodejs 的 phantom-crawler。我将以下脚本复制并粘贴到一个名为 crawler.js 的文件中:

var Crawler = require('phantom-crawler');

// Can be initialized with optional options object 
var crawler = new Crawler();
// queue is an array of URLs to be crawled 
crawler.queue.push('https://google.com/');
// Can also do `crawler.fetch(url)` instead of pushing it and crawling it 
// Extract plainText out of each phantomjs page 
Promise.all(crawler.crawl())
.then(function(pages) {
  var texts = [];
  for (var i = 0; i < pages.length; i++) {
    var page = pages[i];
    // suffix Promise to return promises instead of callbacks 
    var text = page.getPromise('plainText');
    texts.push(text);
    text.then(function(p) {
      return function() {
        // Pages are like tabs, they should be closed 
        p.close()
      }
    }(page));
  }
  return Promise.all(texts);
})
.then(function(texts) {
  // texts = array of plaintext from the website bodies 
  // also supports ajax requests 
  console.log(texts);
})
.then(function () {
  // kill that phantomjs bridge 
  crawler.phantom.then(function (p) {
    p.exit();
  });
})

我想将完整的 html 源代码(在本例中来自 google 页面)打印到控制台。

我搜索了很多,但我没有找到类似的东西,那么我该怎么做呢?

【问题讨论】:

    标签: javascript node.js web-crawler


    【解决方案1】:

    获取content 而不是plainText 承诺。

    模块phantom-crawler使用模块node-phantom-simple,后者使用phantomjs

    您可以在phantomjs wiki 中找到可以调用的属性列表。

    var Crawler = require('phantom-crawler');
    
    // Can be initialized with optional options object
    var crawler = new Crawler();
    // queue is an array of URLs to be crawled
    crawler.queue.push('https://google.com/');
    // Can also do `crawler.fetch(url)` instead of pushing it and crawling it
    // Extract plainText out of each phantomjs page
    Promise.all(crawler.crawl())
    .then(function(pages) {
      var allHtml = [];
      for (var i = 0; i < pages.length; i++) {
        var page = pages[i];
        // suffix Promise to return promises instead of callbacks
        var html = page.getPromise('content');
        allHtml.push(html);
        html.then(function(p) {
          return function() {
            // Pages are like tabs, they should be closed
            p.close()
          }
        }(page));
      }
      return Promise.all(allHtml);
    })
    .then(function(allHtml) {
      // allHtml = array of plaintext from the website bodies
      // also supports ajax requests
      console.log(allHtml);
    })
    .then(function () {
      // kill that phantomjs bridge
      crawler.phantom.then(function (p) {
        p.exit();
      });
    })
    

    【讨论】:

    • 感谢您的详细回答。这很有帮助。
    • 不客气,但你知道我刚刚检查了源代码;)!
    • 我是 node js 技术的新手,我试图弄清楚所有东西是如何协同工作的,相信我我检查了源代码,但我不明白咖啡脚本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多