javascript 如何使用 PhantomJS 提交表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28500775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to submit a form with PhantomJS?
提问by user3416803
I'm getting familiar with PhantomJS. But I can't get one thing. I have a page with a simple form:
我开始熟悉 PhantomJS。但我不能得到一件事。我有一个带有简单表单的页面:
<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
和 save.php 只是写下 test_data 值
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.
呈现页面时,我看到文本字段为 555,但表单未提交且 save.php 未记下 test_data 值。所以doSubmit()
不是执行,是吗?doSubmit()
是一个简单的验证步骤,提交应该加载下一页。
So the question is: how can I execute a javascript code on the page, using PhantomJS?
所以问题是:如何使用 PhantomJS 在页面上执行 javascript 代码?
回答by Artjom B.
It seems that you want to submit the form. You can achieve that in different ways, like
看来您要提交表单。您可以通过不同的方式实现这一目标,例如
- clicking the submit button
submit the formin the page context:
page.evaluate(function() { document.forms[0].submit(); });
or focus on the form text field and send an enter keypress with sendEvent().
- 点击提交按钮
在页面上下文中提交表单:
page.evaluate(function() { document.forms[0].submit(); });
或关注表单文本字段并使用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.onLoadFinished
在提交表单之前注册(然后包含您剩余的脚本)来完成。
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
});