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?
I've had that exact problem. It can be done with a little trickery, because
page.evaluate
also can accept a string.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:And here is the
evaluate()
function:While you can pass arguments into evaluate(function, arg1, arg2, ...), this is often a little cumbersome. Especially in cases when passing in several variables, or worse, functions.
To get around this obstacle, one can use injectJs(filename) instead.
Where
my_extra_functionality.js
is a local file in the same directory:There is the solution that works with PhantomJS 0.9.2 and 0.2.0:
You can pass in the arguments to the function as arguments to page.evaluate.
Example:
This works for me:
Means to put everything as a string. Anyway later it become a string. Check the library source.
Another possibility: pass the variables in with the url. For example, to pass object x