我正在使用 phantomjs 创建页面的 Base64 屏幕截图。我有一些事情,我真的不太明白。这是我的代码:
var webPage = require('webpage');
var page = webPage.create();
page.open('http://example.com', function (status) {
var base64 = page.renderBase64('PNG');
console.log(base64);
phantom.exit();
});
我想知道为什么我不能立即使用 webPage.create() 的结果?
例如,此代码将无法完成:
var webPage = require('webpage');
webPage.create().open('http://example.com', function (status) {
var base64 = page.renderBase64('PNG');
console.log(base64);
phantom.exit();
});
最佳答案
默认情况下,没有名为page
的对象,因此,您需要创建它:
var page = require('webpage').create({viewportSize:{width: 1600,height: 900},
settings:{userAgent:'Mozilla/5.0 (X11; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0',
javascriptEnabled:'true',
loadImages:'true'
}});
之后就可以照常使用了,例如:page.renderBase64('PNG');
或者您可以使用名为 this
的指针(对当前对象的引用):
require('webpage').create().open('http://example.com',function(status){
var base64 = this.renderBase64('PNG');// You can use "this", instead of the object name.
console.log(base64);
phantom.exit();
});
或者相同,但具有 create()
函数的附加设置:
var obj={viewportSize:{width: 1600,height: 900},
settings:{userAgent:'Mozilla/5.0 (X11; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0',
javascriptEnabled:'true',
loadImages:'true'
}}// The additional settings for the create() function.
require('webpage').create(obj).open('http://example.com',function(status){
var base64 = this.renderBase64('PNG');// You can use "this", instead of the object name.
console.log(base64);
phantom.exit();
});
关于javascript - 为什么我不能在 Phantomjs 中直接使用 webPage.create() 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829418/