如何将数据传递给 page.eveluate 函数?
How pass data to page.eveluate function?
考虑来自 node-phantom 的代码:
page.evaluate(function() {
return document.getElementById('foo').innerHTML;
}).then(function(html){
console.log(html);
});
这个函数是直接在html页面执行的,所以加了一个这样的参数:
someExternalVariable = 'foo';
page.evaluate(function() {
return document.getElementById(someExternalVariable).innerHTML;
}).then(function(html){
console.log(html);
});
导致未定义someExternalVariable
,因为打开的页面对someExternalVariable
一无所知。那么如何传递外部数据来评估phantomjs-node中的函数?
如果变量是可序列化的,你可以这样做
someExternalVariable = 'foo';
page.evaluate(function(id) {
return document.getElementById(id).innerHTML;
}, someExternalVariable ).then(function(html){
console.log(html);
})
如果不是(比如你想传递一个带闭包的函数),我怀疑是否有办法做到这一点。 Docs.
Note: The arguments and the return value to the evaluate function must
be a simple primitive object. The rule of thumb: if it can be
serialized via JSON, then it is fine.
考虑来自 node-phantom 的代码:
page.evaluate(function() {
return document.getElementById('foo').innerHTML;
}).then(function(html){
console.log(html);
});
这个函数是直接在html页面执行的,所以加了一个这样的参数:
someExternalVariable = 'foo';
page.evaluate(function() {
return document.getElementById(someExternalVariable).innerHTML;
}).then(function(html){
console.log(html);
});
导致未定义someExternalVariable
,因为打开的页面对someExternalVariable
一无所知。那么如何传递外部数据来评估phantomjs-node中的函数?
如果变量是可序列化的,你可以这样做
someExternalVariable = 'foo';
page.evaluate(function(id) {
return document.getElementById(id).innerHTML;
}, someExternalVariable ).then(function(html){
console.log(html);
})
如果不是(比如你想传递一个带闭包的函数),我怀疑是否有办法做到这一点。 Docs.
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.