如何以编程方式访问java中的网页 [英] How to programmatically access web page in java

查看:96
本文介绍了如何以编程方式访问java中的网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There is a web page from which I want to retrieve a certain string. In order to do so, I need to login, click some buttons, fill a text box, click another button - and then the string appears.

我怎么能写一个java程序自动完成吗?是否有任何有用的库用于此目的?

How can I write a java program to do that automatically? Are there any useful libraries for that purpose?

谢谢

推荐答案

试试 HtmlUnit


HtmlUnit是一个用于
Java程序的GUI-Less浏览器。它模拟HTML
文档并提供一个API,
允许您调用页面,填写
表单,点击链接等...就像你在正常中做的
一样浏览器。

HtmlUnit is a "GUI-Less browser for Java programs". It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc... just like you do in your "normal" browser.

提交表单的示例代码:

@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

这篇关于如何以编程方式访问java中的网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆