【发布时间】:2018-02-23 14:13:05
【问题描述】:
我的目标是使用 Node.js 从网站上抓取一些数据。
我已经设法仅使用 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 中运行时,它不起作用并不断给我错误:
(节点:6576)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):错误:意外的参数类型。期望 args 是数组。
(node:6576) DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。
有什么办法解决这个问题吗?
编辑:
基于@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))
;
【问题讨论】:
标签: javascript node.js npm web-scraping phantomjs