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

dud*_*mar 17 java http

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

如何编写java程序来自动执行此操作?那个目的有没有有用的库?

谢谢

YoK*_*YoK 24

试试HtmlUnit

HtmlUnit是一个"用于Java程序的GUI-Less浏览器".它模拟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();
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请访问:http: //htmlunit.sourceforge.net/gettingStarted.html