【问题标题】:How to use PhantomJS along with node.js for scraping?如何使用 PhantomJS 和 node.js 进行抓取?
【发布时间】:2015-01-30 05:23:08
【问题描述】:

我已经通过npm install node-phantom 安装了node-phantom,但是当我运行这段代码时,它给出了Cannot find module 'webpage' 这个错误

var webpage = require('webpage').create(),
    url = "https://www.example.com/cba/abc",
    hrefs = new Array();
webpage.open(url,function(status){
    if(status=="success"){
        var results = page.evaluate(function(){
            $("#endpoints").each(function() {
                  hrefs.push($(this).attr("href"));
            });
            return hrefs;
        });
        console.log(JSON.stringify(results));
        phantom.exit();
    }
});

【问题讨论】:

  • 查看node_module文件夹中是否存在网页模块

标签: javascript jquery node.js phantomjs


【解决方案1】:

您不需要 node-phantom 中的网页模块。您将使用它的 API 来获取网页模块的表示。必须这样做,因为 PhantomJS 的执行运行时与 node.js 不同。他们通常不能使用相同的模块。这就是为什么在node-phantomphantom 这样的两个执行环境之间存在桥梁的原因。它们本质上复制了 PhantomJS 的 API 以在 node.js 中使用。

根据文档,您不需要网页,而是获得一个页面:

var phantom = require('node-phantom');
phantom.create(function(err,ph) {
  return ph.createPage(function(err,page) {
    // do something with page: basically your script
  });
});

您不能只复制和粘贴现有的 PhantomJS 代码。存在差异,因此您必须研究 API(基本上是 github 上的 README)。

完整翻译您的代码:

var phantom = require('node-phantom');
phantom.create(function(err,ph) {
  return ph.createPage(function(err,page) {
    page.open(url,function(status){
      if(status=="success"){
        page.evaluate(function(){
          hrefs = [];
          $("#endpoints").each(function() {
            hrefs.push($(this).attr("href"));
          });
          return hrefs;
        }, function(err, results){
          console.log(JSON.stringify(results));
          ph.exit();
        });
      }
    });
  });
});

page.evaluate 仍处于沙盒状态,因此您不能使用像 hrefs 这样的外部变量。

【讨论】:

    猜你喜欢
    • 2014-03-18
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多