Example 1: Get the title of the Javaeye Web site
Import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
Import com.gargoylesoftware.htmlunit.WebClient;
Import Com.gargoylesoftware.htmlunit.html.HtmlPage;
public static void Gethometile () throws Failinghttpstatuscodeexception, Malformedurlexception, ioexception{
Final WebClient WebClient = new WebClient ();
Final HtmlPage HtmlPage = webclient.getpage ("http://www.javaeye.com");
System.out.println (Htmlpage.gettitletext ());
System.out.println (Htmlpage.gettextcontent ());
}
You can see print out: Javaeye Java Programming Spring Framework Ajax Technology Agile Agile Software development Ruby on Rails practice-Javaeye do the best software development communication community
Same as the title property of the Javaeye home page
Example two: Getting a specific browser version
public void Homepage_firefox () throws Exception {
Final WebClient WebClient = new WebClient (browserversion.firefox_2);
Final HtmlPage page = webclient.getpage ("http://htmlunit.sourceforge.net");
Assertequals ("Htmlunit-welcome to Htmlunit", Page.gettitletext ());
}
Example three: Get a div or anchor connection for a specific ID
public void GetElements () throws Exception {
Final WebClient WebClient = new WebClient ();
Final HtmlPage page = webclient.getpage ("Http://some_url");
Final HTMLDivision div = Page.gethtmlelementbyid ("some_div_id");
Final HtmlAnchor anchor = page.getanchorbyname ("Anchor_name");
}
Example four: Simulate a page to submit a form
public void Submittingform () throws Exception {
Final WebClient WebClient = new WebClient ();
Get the 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 "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" button and get back the second page.
Final HtmlPage Page2 = Button.Click ();
}