Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically access web page in java

Tags:

java

http

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.

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

Thanks

like image 306
duduamar Avatar asked Aug 23 '10 17:08

duduamar


People also ask

How do you programmatically click a button on a website?

You can't 'programmatically' click a button with Java alone, which is why we use JavaScript. If you want to get into controlling the browser such as clicking buttons and filling text fields you would have to use an automation tool. An automation tool that uses Java is Selenium.


1 Answers

Try HtmlUnit

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.

Example code for submiting form:

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

For more details check: http://htmlunit.sourceforge.net/gettingStarted.html

like image 83
YoK Avatar answered Sep 19 '22 07:09

YoK