How to submit a form with PhantomJS?

15,803

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

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
});
Share:
15,803
user3416803
Author by

user3416803

Updated on June 22, 2022

Comments

  • user3416803
    user3416803 almost 2 years

    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?