File tree Expand file tree Collapse file tree
spring-mvc-java/src/test/java/com/baeldung/htmlunit Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .htmlunit ;
2+
3+ import java .util .List ;
4+
5+ import com .gargoylesoftware .htmlunit .WebClient ;
6+ import com .gargoylesoftware .htmlunit .html .HtmlAnchor ;
7+ import com .gargoylesoftware .htmlunit .html .HtmlHeading1 ;
8+ import com .gargoylesoftware .htmlunit .html .HtmlHeading2 ;
9+ import com .gargoylesoftware .htmlunit .html .HtmlPage ;
10+
11+ public class HtmlUnitWebScraping {
12+
13+ public static void main (final String [] args ) throws Exception {
14+ try (final WebClient webClient = new WebClient ()) {
15+
16+ webClient .getOptions ().setCssEnabled (false );
17+ webClient .getOptions ().setJavaScriptEnabled (false );
18+
19+ final HtmlPage page = webClient .getPage ("http://www.baeldung.com/full_archive" );
20+ final HtmlAnchor latestPostLink = (HtmlAnchor ) page .getByXPath ("(//ul[@class='car-monthlisting']/li)[1]/a" ).get (0 );
21+
22+ System .out .println ("Entering: " + latestPostLink .getHrefAttribute ());
23+
24+ final HtmlPage postPage = latestPostLink .click ();
25+
26+ final HtmlHeading1 heading1 = (HtmlHeading1 ) postPage .getByXPath ("//h1" ).get (0 );
27+ System .out .println ("Title: " + heading1 .getTextContent ());
28+
29+ final List <HtmlHeading2 > headings2 = (List <HtmlHeading2 >) postPage .getByXPath ("//h2" );
30+
31+ final StringBuilder sb = new StringBuilder (heading1 .getTextContent ());
32+ for (final HtmlHeading2 h2 : headings2 ) {
33+ sb .append ("\n " ).append (h2 .getTextContent ());
34+ }
35+
36+ System .out .println (sb .toString ());
37+ }
38+ }
39+
40+ }
You can’t perform that action at this time.
0 commit comments