如何在Java中通过编程方式访问网页

20

我想要从一个网页中检索特定的字符串。为此,我需要登录,点击一些按钮,填写文本框,再点击另一个按钮-然后字符串就出现了。

我该如何编写Java程序以自动完成这些操作?是否有相关的有用库可供使用?

谢谢


通常情况下,使用官方的 API 比屏幕抓取效果要好。你想要访问哪个网站? - Thorbjørn Ravn Andersen
我不相信这个网站有官方的API,但我也会检查一下这个选项。 - duduamar
5个回答

27

尝试使用HtmlUnit

HtmlUnit是一个“无界面浏览器”,适用于Java程序。它模拟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


这正是我一直在寻找的。我会查阅一下,谢谢! - duduamar
它也相当缓慢,而且警告消息非常宽松。 - SuperJedi224
1
太棒了!通过这种方法,我能够制作一个Java应用程序,访问我的银行公司的网站,使用我的凭据进行登录,并以完全自动化的方式管理将我的银行账户余额和交易记录输出到Java控制台中! - user3289695
投票向下一格。我正在寻找类似的东西,但请不要告诉我有些不可用的“框架”。如何使用POJO完成? - Baruch Atta

2
这个问题可以通过使用HtmlUnit来轻松解决,具体步骤如下:
1. 访问http://htmlunit.sourceforge.net/
2. 根据需要进行下载和安装。
3. 在代码中调用相关函数即可。
@Test
public void homePage() throws Exception {
    final WebClient webClient = new WebClient();
    final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
    assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
}

1

看一下 Apache HttpClient 项目,或者如果你需要在页面上运行 JavaScript,可以尝试使用 HttpUnit


0
通常情况下,当您按下按钮时,会通过HTTP POST方法发送请求,因此您应该使用HttpClient来处理请求,并使用HtmlParser处理响应页面以获取所需的字符串。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接