Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phantomjs - How to populate a form, submit and get the results?

Tags:

phantomjs

I can't seem to do a simple form submit.

Below is the code that I did to submit "Test" to the Google search form and print out the results.

var url = 'http://www.google.com/',
    page = new WebPage();

page.open(url, function(status) {
    if (status !== 'success')
    {
      console.log('Unable to access network');
      phantom.exit();
      return;
    }
    else
    {
        page.includeJs("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function() {
            page.evaluate(function() {
                $('#gbqfq').val("Test");

                $("#gbqfba").click();

            });

            page.render('google.png');
            phantom.exit();
        });
    }
});

Anyone can show me how to do this? I have looked around here and in other sites but nothing seemed to work.

like image 896
developarvin Avatar asked May 22 '13 08:05

developarvin


1 Answers

It isn't sufficient to render a page immediately after "clicking". You have to give the web engine time to make whatever calls are required and execute the resulting JavaScript.

Consider the following after your call to evaluate:

window.setTimeout(
  function () {
    page.render( 'google.png' );
    phantom.exit(0);
  },
  5000 // wait 5,000ms (5s)
);

By the way - the click may or may not work depending on what kind of element it is. If that doesn't work I suggest you search the Internet for how to click on a DIV or whatever type of element it happens to be (there is a technique which involves creating a mouse event).

like image 91
PP. Avatar answered Nov 10 '22 00:11

PP.