Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit a form with PhantomJS?

I'm getting familiar with PhantomJS. But I can't get one thing. I have a page with a simple form:

<FORM action="save.php" enctype="multipart/form-data" method="GET" onSubmit="return doSubmit();">
    <INPUT name="test_data" type="text">
    <INPUT name="Submit" type="submit" value="Submit">
</FORM>

and a save.php just writes down the test_data value

so I'm doing this:

page.evaluate(function() {
    document.forms[0].test_data.value="555";
    doSubmit();
});

When rendering the page I see that text field is 555, but form isn't submitting and save.php didn't write down a test_data value. So doSubmit() is not executing, is it? doSubmit() is a simple validation step and a submit is supposed to load the next page.

So the question is: how can I execute a javascript code on the page, using PhantomJS?

like image 945
user3416803 Avatar asked Feb 13 '15 13:02

user3416803


1 Answers

It seems that you want to submit the form. You can achieve that in different ways, like

  • clicking the submit button
  • submit the form in the page context:

    page.evaluate(function() {
        document.forms[0].submit();
    });
    
  • or focus on the form text field and send an enter keypress with sendEvent().

After that you will have to wait until the next page is loaded. This is best done by registering page.onLoadFinished (which then contains your remaining script) right before submitting the form.

page.open(url, function(){
    page.onLoadFinished = function(){
        page.render("nextPage.png");
        phantom.exit();
    };
    page.evaluate(function() {
        document.forms[0].test_data.value="555";
        document.forms[0].submit();
    });
});

or you can simply wait:

page.open(url, function(){
    page.evaluate(function() {
        document.forms[0].test_data.value="555";
        document.forms[0].submit();
    });
    setTimeout(function(){
        page.render("nextPage.png");
        phantom.exit();
    }, 5000); // 5 seconds
});
like image 193
Artjom B. Avatar answered Nov 09 '22 03:11

Artjom B.