2017-09-14 164 views
1

我的目标是使用Node.js从网站上刮取一些数据。PhantomJS错误:UnhandledPromiseRejectionWarning

我已经设法只使用request包抓取数据,但我想抓取的网站有动态内容,而且request只能抓住这个动态数据。

所以我做了一些研究,结果发现,要实现这一目标,总部设在this SO question,我需要通过安装一些软件包npm我不知道,如果这三个都需要):

基于这个问题也一样,我使用相同的代码,只是为了了解它是如何工作:

myFile.js

var phantom = require('phantom'); 

phantom.create(function (ph) { 
    ph.createPage(function (page) { 
    var url = "http://www.bdtong.co.kr/index.php?c_category=C02"; 
    page.open(url, function() { 
     page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() { 
     page.evaluate(function() { 
      $('.listMain > li').each(function() { 
      console.log($(this).find('a').attr('href')); 
      }); 
     }, function(){ 
      ph.exit() 
     }); 
     }); 
    }); 
    }); 
}); 

但是,当我尝试在终端$ node myFile.js运行,它不工作和不断给我的错误:

(node:6576) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Unexpected type of parameters. Expecting args to be array.

(node:6576) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

任何想法如何解决这个问题?

编辑:

最终解决方案基于@Shyam答案(解决)中的错误和this example

var phantom = require('phantom'); 
var _ph, _page, _outObj; 

phantom 
    .create() 
    .then(ph => { 
    _ph = ph; 
    return _ph.createPage(); 
    }) 
    .then(page => { 
    _page = page; 
    return _page.open('https:/www.google.com.br/'); 
    }) 
    .then(status => { 
    console.log(status); 
    return _page.property('content'); 
    }) 
    .then(content => { 
    console.log(content); 
    _page.close(); 
    _ph.exit(); 
    }) 
    .catch(e => console.log(e)) 
; 

回答

3

我不知道你在哪里得到了格式,但最新的幻影JS做不使用回调,而是使用承诺。并且constructor(Phantom.create)需要数组形式的配置,而不是回调函数。

你的代码需要类似于这个我认为(我没有测试过,但应该运行)。

var phantom = require('phantom'); 
var _ph, _page; 
phantom.create() 
    .then(function (ph) { 
    _ph = ph; 
    return ph.createPage(); 
    }) 
    .then(function (page) { 
    _page = page; 
    var url = "http://www.bdtong.co.kr/index.php?c_category=C02"; 
    return page.open(url); 
    }) 
    .then(function(page) { 
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() { 
     page.evaluate(function() { 
     $('.listMain > li').each(function() { 
      console.log($(this).find('a').attr('href')); 
     }); 
     }); 
    }); 
    }) 
    .catch(function(err) { 
    _page.close(); 
    _ph.exit(); 
    }) 
+0

我是不是能够得到与您的解决方案的结果页面中,我只收到一个字符串“成功”,但你的代码帮助给我解决这个问题的方式,使用[这个例子]( https://github.com/amir20/phantomjs-node/blob/master/examples/simple.js)在github。不幸的是,我仍然无法获得页面的动态内容,只返回静态内容和js函数,但这不是这个问题的一部分。谢谢! – Lioo