使用page.evaluate传递参数

The*_*ist 53 javascript phantomjs

我正在使用PhantomJS page.evaluate()进行一些抓取.我的问题是我传递给webkit页面的代码是沙箱,因此无法访问我的主幻像脚本的变量.这使得抓取代码难以通用.

page.open(url, function() {
  var foo = 42;

  page.evaluate(function() {
    // this code has no access to foo
    console.log(foo);
  });
}
Run Code Online (Sandbox Code Playgroud)

我如何将参数推入页面?

Wes*_*ton 72

我遇到了那个确切的问题.它可以用一点技巧来完成,因为它page.evaluate也可以接受一个字符串.

有几种方法可以做到,但是我使用了一个名为的包装器evaluate,它接受附加的参数传递给必须在webkit端评估的函数.你会像这样使用它:

page.open(url, function() {
  var foo = 42;

  evaluate(page, function(foo) {
    // this code has now has access to foo
    console.log(foo);
  }, foo);
});
Run Code Online (Sandbox Code Playgroud)

这是evaluate()功能:

/*
 * This function wraps WebPage.evaluate, and offers the possibility to pass
 * parameters into the webpage function. The PhantomJS issue is here:
 * 
 *   http://code.google.com/p/phantomjs/issues/detail?id=132
 * 
 * This is from comment #43.
 */
function evaluate(page, func) {
    var args = [].slice.call(arguments, 2);
    var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
    return page.evaluate(fn);
}
Run Code Online (Sandbox Code Playgroud)


小智 68

已推送更改,现在您可以将其用作

page.open(url, function() {
  var foo = 42;

  page.evaluate( function(foo) {
  // this code has now has access to foo
  console.log(foo);
  }, foo);
}
Run Code Online (Sandbox Code Playgroud)

推送详情如下:https://github.com/ariya/phantomjs/commit/81794f9096

  • 你能提供一个传递多个参数的例子吗? (5认同)

小智 9

您可以将参数传递给函数作为 page.evaluate 的参数。

例子:

page.evaluate(function(arg1, arg2){
    console.log(arg1); //Will print "hi"
    console.log(arg2); //Will print "there"
}, "hi", "there");
Run Code Online (Sandbox Code Playgroud)