41 lines
1.5 KiB
Java
Raw Normal View History

2016-08-01 10:45:10 +02:00
package com.baeldung.htmlunit;
import java.util.List;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlHeading1;
import com.gargoylesoftware.htmlunit.html.HtmlHeading2;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitWebScraping {
2016-10-12 08:00:02 +03:00
public static void main(final String[] args) throws Exception {
try (final WebClient webClient = new WebClient()) {
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(false);
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive");
final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0);
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
System.out.println("Entering: " + latestPostLink.getHrefAttribute());
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
final HtmlPage postPage = latestPostLink.click();
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0);
System.out.println("Title: " + heading1.getTextContent());
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
final List<HtmlHeading2> headings2 = (List<HtmlHeading2>) postPage.getByXPath("//h2");
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
final StringBuilder sb = new StringBuilder(heading1.getTextContent());
for (final HtmlHeading2 h2 : headings2) {
sb.append("\n").append(h2.getTextContent());
}
2016-08-01 10:45:10 +02:00
2016-10-12 08:00:02 +03:00
System.out.println(sb.toString());
}
}
2016-08-01 10:45:10 +02:00
}