node.js - PhantomJS includeJS 不工作
问题描述
我正在尝试使用PhantomJS
以从这样的网站获取数据:
app.get('/scrape', function(req, res) {
var _ph, _page;
phantom.create()
.then(function (ph) {
_ph = ph;
return ph.createPage();
})
.then(function (page) {
_page = page;
var url = "https://banc.nl/";
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() {
$('.sc-dnqmqq kaMmif').filter(function () {
var data = $(this);
price = data.children().first().text();
console.log("Price: " + price);
});
});
});
})
.catch(function(err) {
console.log("Error: " , err);
_page.close();
//_ph.exit();
});
});
问题是我收到以下错误:Error: TypeError: page.includeJs is not a function
如果我取消注释,ph.exit()
我也会收到警告:warn: exit() was called before waiting for commands to finish. Make sure you are not calling exit() prematurely.
我在 SO 中发现了几个关于此的问题,但没有一个答案解决了我的问题。
解决方案
最新版本的phantomjs-node模块使用了 Promises,因此我们可以使用async
带有await
操作符的函数重写脚本——更具可读性:
var phantom = require('phantom');
var url = 'https://www.huobipro.com';
(async function(req, res) {
const instance = await phantom.create();
const page = await instance.createPage();
await page.on('onConsoleMessage', function(msg) {
console.info(msg);
});
await page.on('onError', function(msg) {
console.info(msg);
});
const status = await page.open(url);
await console.log('STATUS:', status);
// Wait a bit for javascript to load and run
await new Promise(resolve => setTimeout(resolve, 3000))
await page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js');
await page.evaluate(function() {
$('span[price]').filter(function () {
var data = $(this);
console.log("Price: " + data.text());
});
});
await instance.exit();
})();
推荐阅读
- python - 如何在 Python 中进行 Gamma 分布?
- python-3.x - sudo:python3:找不到命令
- python - 如何在龙卷风python应用程序上添加速率限制
- javascript - Web 应用程序(Vue js,Laravel 8):在 Safari iOS 中滚动的最小视图
- asp.net-core - 未处理的异常。System.InvalidOperationException:JsonConvert.Deserialize() 的 LINQ 表达式错误
- python - 我如何解决 Pandas groupby 函数?
- twilio - 在选定设备中使用手机后置摄像头的 Twilio 可编程视频?
- typescript - 为什么这个Schema为空.....如何在nestjs中设置@ApiProperty
- r - 如何解决R语言使用write.xlsx()将数据写入excel文档的字符变化问题?
- sqlalchemy - 从 psycopg 连接创建 sqlalchemy 引擎