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

use*_*639 14 java htmlunit

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

我已经检查了javadoc并且没有找到任何方法来做到这一点.奇怪的是HtmlForm中没有这样的功能......


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

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

小智 41

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

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();
Run Code Online (Sandbox Code Playgroud)


Mar*_*tin 7

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);
Run Code Online (Sandbox Code Playgroud)


Ran*_*ggs 1

final HtmlSubmitInput button = form.getInputByName("submitbutton");
final HtmlPage page2 = button.click()
Run Code Online (Sandbox Code Playgroud)

来自htmlunit 文档

@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();
}
Run Code Online (Sandbox Code Playgroud)

  • OP已编辑,现在它说没有提交按钮。 (2认同)