繁体   English   中英

如何使用PhantomJS和node.js进行抓取?

[英]How to use PhantomJS along with node.js for scraping?

我已经通过npm install 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-phantom中使用网页模块。 您将使用其API来获取网页模块的表示形式。 必须这样做,因为PhantomJS与node.js具有不同的执行运行时。 他们通常不能使用相同的模块。 这就是为什么在这两个执行环境(例如node-phantomphantom)之间建立桥梁的原因。 他们本质上复制了在node.js中使用的PhantomJS API。

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

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这样使用外部变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM