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

时间:2011-09-27 17:54:30

标签: java htmlunit

我知道在HtmlUnit中我可以fireEvent在表单上提交,然后发布。但是如果我禁用了javascript并希望使用一些内置函数发布表单?

我已经检查了javadoc并且没有找到任何方法来执行此操作。很奇怪HtmlForm中没有这样的功能......


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

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

4 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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);

答案 2 :(得分:2)

final HtmlSubmitInput button = form.getInputByName("submitbutton");
final HtmlPage page2 = button.click()

来自the 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();
}

答案 3 :(得分:1)

如何使用内置的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();