Adnan Yaseen
Adnan Yaseen

Reputation: 853

Run Javascript custom function in PhantomJS

I am writing a console application in which I am using Nreco.PhantomJS to load the data. This is a scrapping application for a website containing google map with markers on it. The data I am trying to get is not available on the page before or after it is loaded completely. The data is the simple Latitude and Longitude that is passed from a JavaScript function to the google map and is not rendered on the page. As I am very new to PhantomJS so I am not sure how to achieve this but I am sure this can be done. This small piece of script is run by me in c# code,

try
{
    string jsContent = "var system = require('system');" +
    "var page = require('webpage').create();" +
    "page.open('" + url + "', function(status) {" +

        "system.stdout.writeLine(GetLatLang());" +
    "}"+

    "phantom.exit();" +
    "});";

    phantomJS.RunScript(jsContent, null, null, ms);
}
finally
{
    phantomJS.Abort(); // ensure that phantomjs.exe is stopped
}

When I call Alert(GetLatLang()) function in console tab (Inside google chrome inspector) then it run fines and value is retrieved. However the PhantomJS never finishes running the code and I have to close the application. My understanding is that in the above code PhantomJS immediately try to execute the GetLatLang() function whereas it is not available at that time. Is there any way to execute this function after the page is completely loaded?

Upvotes: 0

Views: 1036

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

You need to call the GetLatLang() function in the page context and not in the phantom context:

"page.open('" + url + "', function(status) {" +
    "console.log(page.evaluate(function(){" +
        "return GetLatLang();" +
    "}));" +
"}"+

page.evaluate() is the only function that provides access to the DOM and the page's window object.


Additionally, your JavaScript has a syntax error. There is only one opening {, but two closing }. You need to remove "}"+.

Upvotes: 1

Related Questions