当我从命令行node script.js
运行下面的脚本时,结果是:
success
Promise { <pending> }
页面永远不会在console.log
中打开,任何人都可以解释原因吗?
var phantom = require('phantom');
phantom.create().then(function (ph) {
ph.createPage().then(function (page) {
page.open('https://stackoverflow.com/').then(function (status) {
console.log(status);
var p = page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML
});
console.log(p);
});
});
});
答案 0 :(得分:1)
那是因为您将Promise分配给变量,并且不会立即返回结果。你应该宁愿:
page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
}).then(function (html) {
console.log(html);
});
另外,为避免迷失在回调地狱中,您可能会尝试使用async/await
方法:
(async () => {
const instance = await phantom.create();
const page = await instance.createPage();
const status = await page.open('https://stackoverflow.com/');
const html = await page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML;
});
console.log(html);
})();
根据phantom维护者指南,这是一种首选方式。
答案 1 :(得分:1)
,page.evaluate返回一个promise。
尝试下面的代码:
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open('https://stackoverflow.com/').then(function(status) {
console.log('test'+status);
var p = page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML
});
p.then(function(pagecontent) {
console.log(pagecontent);
process.exit()
});
});
});
});