使用page.evaluate传递参数 [英] Pass arguments with page.evaluate

查看:686
本文介绍了使用page.evaluate传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using PhantomJS page.evaluate() to do some scraping. My problem is that the code I pass to the webkit page is sandboxed, and so has no access to the variables of my main phantom script. This makes it hard make the scraping code generic.

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

  page.evaluate(function() {
    // this code has no access to foo
    console.log(foo);
  });
}

我如何将参数推入页面?

How could I push arguments into the page?

推荐答案

我遇到了确切的问题。可以通过一点点诡计来完成,因为 page.evaluate 也可以接受一个字符串。

I've had that exact problem. It can be done with a little trickery, because page.evaluate also can accept a string.

有几种方法可以做到,但我使用一个名为 evaluate ,接受其他参数传递给必须在webkit端评估的函数。你可以这样使用它:

There are several ways to do it, but I use a wrapper called evaluate, which accepts additional parameters to pass to the function that must be evaluated on the webkit side. You would use it like this:

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

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

这是 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);
}

这篇关于使用page.evaluate传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆