HtmlUnit,如何在不单击提交按钮的情况下发布表单?

我知道在HtmlUnit中我可以在表单上提交fireEvent并将其发布。 但是如果我禁用了javascript并想使用一些内置函数发布表单呢?

我检查了javadoc并且没有找到任何方法来做到这一点。 奇怪的是HtmlForm中没有这样的function……


我在htmlunit页面上阅读了javadoc和教程,我知道我可以使用getInputByName()并单击它。 BuT有时会有没有提交类型按钮的表单,甚至没有这样的按钮但没有name属性。

我在这种情况下寻求帮助,这就是我使用fireEvent但它并不总是有效的原因。

您可以使用“临时”提交按钮:

 WebClient client = new WebClient(); HtmlPage page = client.getPage("http://stackoverflow.com"); // create a submit button - it doesn't work with 'input' HtmlElement button = page.createElement("button"); button.setAttribute("type", "submit"); // append the button to the form HtmlElement form = ...; form.appendChild(button); // submit the form page = button.click(); 
 WebRequest requestSettings = new WebRequest(new URL("http://localhost:8080/TestBox"), HttpMethod.POST); // Then we set the request parameters requestSettings.setRequestParameters(Collections.singletonList(new NameValuePair(InopticsNfcBoxPage.MESSAGE, Utils.marshalXml(inoptics, "UTF-8")))); // Finally, we can get the page HtmlPage page = webClient.getPage(requestSettings); 
 final HtmlSubmitInput button = form.getInputByName("submitbutton"); final HtmlPage page2 = button.click() 

来自htmlunit doc

 @Test public void submittingForm() throws Exception { final WebClient webClient = new WebClient(); // Get the first page final HtmlPage page1 = webClient.getPage("http://some_url"); // Get the form that we are dealing with and within that form, // find the submit button and the field that we want to change. final HtmlForm form = page1.getFormByName("myform"); final HtmlSubmitInput button = form.getInputByName("submitbutton"); final HtmlTextInput textField = form.getInputByName("userid"); // Change the value of the text field textField.setValueAttribute("root"); // Now submit the form by clicking the button and get back the second page. final HtmlPage page2 = button.click(); webClient.closeAllWindows(); } 

如何使用内置的JavaScript支持? 只需在该表单上触发提交事件:

 HtmlForm form = page.getForms().get(0); form.fireEvent(Event.TYPE_SUBMIT); 

代码假设您要在网站上提交第一个表单。

如果提交将您转发到另一个站点,只需将响应链接到页面变量:

 HtmlForm form = page.getForms().get(0); page = (HtmlPage) form.fireEvent(Event.TYPE_SUBMIT).getNewPage(); 

尽管这个问题具有良好且有效的答案,但似乎没有一个人能够很好地模仿真实的用户行为。
想想看:当没有按钮点击时,人类做了什么? 很简单,你点击输入(返回)。 这就是它在HtmlUnit中的工作原理:

 // assuming page holds your current HtmlPage HtmlForm form = page.getFormByName("yourFormName"); HtmlTextInput input = form.getInputByName("yourTextInputName"); // type something in input.type("here goes the input"); // now hit enter and get the new page page = (HtmlPage) input.type('\n'); 

注意input.type("\n");input.type('\n');

当您禁用了javascript exection并且没有可用的提交按钮时,此方法有效。


恕我直言,你应该首先想到你想如何提交表格。 你想测试什么场景? 用户点击返回可能是单击某个按钮(可能有一些onClick)的不同情况。 通过JavaScript提交表单可能是另一个测试用例。

当你想出来从其他答案(当然这是一个)中选择适当的方式提交你的表格。