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

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

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

谢谢

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

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

执行此操作的超级简单方法是在此处使用HtmlUnit:

http://htmlunit.sourceforge.net/

你想做的事情可以简单到:

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

看看apache HttpClient项目,或者如果你需要在页面上运行Javascript,请尝试HttpUnit 。

通常,当您按下按钮时,您通过HTTP POST方法执行请求,因此您应该使用HttpClient来处理请求,并使用HtmlParser来处理具有您需要的字符串的响应页面。

是:

  • java.net.URL#openConnection()将允许您发出http请求并获取http响应

  • Apache HttpComponents是一个可以更轻松地使用HTTP的库。