小编典典

如何以编程方式访问Java中的网页

java

有一个网页,我想从中检索某个字符串。为此,我需要登录,单击一些按钮,填充文本框,单击另一个按钮-然后出现字符串。

如何编写Java程序以自动执行此操作?是否有用于此目的的有用库?

谢谢


阅读 260

收藏
2020-12-03

共1个答案

小编典典

试试HtmlUnit

HtmlUnit是“用于Java程序的GUI更少的浏览器”。它为HTML文档建模,并提供一个API,使您可以调用页面,填写表单,单击链接等,就像在“常规”浏览器中一样。

提交表单的示例代码:

@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();
}

有关更多详细信息,请检查:http :
//htmlunit.sourceforge.net/gettingStarted.html

2020-12-03