Skip to content

Commit c77c3ba

Browse files
committed
Add web scraping post with jsoup
1 parent 78d03a9 commit c77c3ba

4 files changed

Lines changed: 63 additions & 16 deletions

File tree

‎stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/post/PostData.java‎

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -529,21 +529,30 @@ public class PostData {
529529
))
530530
.build()
531531
);
532-
// posts.add(PostRaw.builder()
533-
// .postId(877736688294485954L)
534-
// .title("Web Scraping in Java using jsoup and OkHttp")
535-
// .metaDesc("jsoup example scraping the DOM using CSS selectors and OkHttpClient for networking.")
536-
// .dateCreated(LocalDateTime.parse("2017-06-22T10:15:30"))
537-
// .dateUpdated(LocalDateTime.parse("2017-06-22T10:15:30"))
538-
// .javaLibs(Lists.newArrayList(JavaLib.OkHttp, JavaLib.jsoup, JavaLib.Failsafe, JavaLib.jOOλ, JavaLib.Guava))
539-
// .tags(Lists.newArrayList(Tags.HTTP, Tags.HtmlTemplating))
540-
// .gitFileReferences(Lists.newArrayList(
541-
// FileReference.stubbornJava(
542-
// "httpClient",
543-
// "stubbornjava-common/src/main/java/com/stubbornjava/common/HttpClient.java")
544-
// ))
545-
// .build()
546-
// );
532+
posts.add(PostRaw.builder()
533+
.postId(877736688294485954L)
534+
.title("Web Scraping in Java using jsoup and OkHttp")
535+
.metaDesc("jsoup example scraping the DOM using CSS selectors and OkHttpClient for networking.")
536+
.dateCreated(LocalDateTime.parse("2017-06-22T10:15:30"))
537+
.dateUpdated(LocalDateTime.parse("2017-06-22T10:15:30"))
538+
.javaLibs(Lists.newArrayList(JavaLib.OkHttp, JavaLib.jsoup, JavaLib.Failsafe, JavaLib.jOOλ, JavaLib.Guava))
539+
.tags(Lists.newArrayList(Tags.HTTP, Tags.HtmlTemplating))
540+
.gitFileReferences(Lists.newArrayList(
541+
FileReference.stubbornJava(
542+
"model",
543+
"stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/themes/HtmlCssTheme.java")
544+
, FileReference.stubbornJava(
545+
"scraper",
546+
"stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/themes/WrapBootstrapScraper.java")
547+
, FileReference.stubbornJava(
548+
"service",
549+
"stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/themes/Themes.java")
550+
, FileReference.stubbornJava(
551+
"routes",
552+
"stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/themes/ThemeRoutes.java")
553+
))
554+
.build()
555+
);
547556
}
548557

549558
public static List<PostRaw> getPosts() {

‎stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/themes/Themes.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ private Themes() {}
3535
private static final List<HtmlCssTheme> fetchPopularThemes() {
3636
return Seq.seq(suppliers)
3737
.map(sup -> {
38+
/*
39+
* If one fails we don't want them all to fail.
40+
* This can be handled better but good enough for now.
41+
*/
3842
try {
3943
return sup.get();
4044
} catch (Exception ex) {

‎stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/themes/WrapBootstrapScraper.java‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,16 +31,23 @@ public class WrapBootstrapScraper {
3131
public static List<HtmlCssTheme> popularThemes() {
3232
HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL);
3333
Request request = new Request.Builder().url(url).get().build();
34+
// Retry if the request is not successful code >= 200 && code < 300
3435
String html = Retry.retryUntilSuccessfulWithBackoff(
3536
() -> client.newCall(request).execute()
3637
);
3738

39+
// Select all the elements with the given CSS selector.
3840
Elements elements = Jsoup.parse(html).select("#themes .item");
39-
List<HtmlCssTheme> themes = Seq.seq(elements).map(WrapBootstrapScraper::themeFromElement).toList();
41+
List<HtmlCssTheme> themes = Seq.seq(elements)
42+
.map(WrapBootstrapScraper::themeFromElement)
43+
.toList();
4044

4145
return themes;
4246
}
4347

48+
/*
49+
* Parse out the data from each Element
50+
*/
4451
private static HtmlCssTheme themeFromElement(Element element) {
4552
Element titleElement = element.select(".item_head h2 a").first();
4653
String title = titleElement.text();
@@ -56,6 +63,10 @@ private static HtmlCssTheme themeFromElement(Element element) {
5663
return new HtmlCssTheme(title, url, imageUrl, downloads);
5764
}
5865

66+
/*
67+
* Main methods everywhere! Very convenient for quick ad hoc
68+
* testing without spinning up an entire application.
69+
*/
5970
public static void main(String[] args) {
6071
List<HtmlCssTheme> themes = popularThemes();
6172
log.debug(Json.serializer().toPrettyString(themes));
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<div class="anchored-md">
2+
{{#assign "markdown"}}
3+
Web scraping is a fundamental skill that is extremely useful for data collection and automating tasks. The following examples will show how we scrape sites such as [wrapbootstrap](https://wrapbootstrap.com/?ref=stubbornjava) and [themeforest](https://themeforest.net/?ref=StubbornJava) to populate the [HTML/CSS Theme Templates](/best-selling-html-css-themes-and-website-templates) page. We will be using [jsoup](https://jsoup.org/) for DOM parsing and [OkHttp](http://square.github.io/okhttp/) for HTTP. Although jsoup is capable of handling HTTP for us we prefer to stick with OkHttp incase we need anything more complex than a simple GET request such as special headers and cookies. Why learn two libraries when one will do?
4+
{{/assign}}
5+
{{md markdown}}
6+
</div>
7+
8+
<h2 class="anchored">Model / POJO</h2>
9+
</p>We like to start simple so we are only gathering four fields title, url, image url, and number of downloads if available.</p>
10+
{{> templates/src/widgets/code/code-snippet file=model section=model.sections.model}}
11+
12+
<h2 class="anchored">jsoup Scraper</h2>
13+
<p>Our scraper is fairly simple. All it needs to do is a single GET request and extract the data we are interested in. We are using <a href="https://github.com/jhalterman/failsafe#retries">failsafe</a> for retry logic and <a href="https://github.com/jOOQ/jOOL">jOOλ</a> for a simplified streaming api. Setting up <a href="/posts/okhttpclient-logging-configuration-with-interceptors">OkHttpClient Logging Interceptors</a> is very useful for tracking down bugs. We are only showing the <a href="https://wrapbootstrap.com/?ref=stubbornjava">wrapbootstrap</a> scraper but the rest can be found <a href="https://github.com/StubbornJava/StubbornJava/tree/master/stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/themes">here</a>.</p>
14+
{{> templates/src/widgets/code/code-snippet file=scraper section=scraper.sections.scraper}}
15+
16+
<h2 class="anchored">Theme Service layer</h2>
17+
<p>Our naming convention for the service layer is generally jut pluralizing the model. We don't care how it's getting the data as long as it gets it. We are caching the results of each scraper so we don't upset the websites maintainers. In a more ideal world we might periodically scrape and store the data in our own database.</p>
18+
{{> templates/src/widgets/code/code-snippet file=service section=service.sections.themes}}
19+
20+
<h2 class="anchored">Theme Routes</h2>
21+
<p>Now we simply create a custom <a href="/posts/undertow-writing-custom-httphandlers">HttpHandler</a> and pass the themes along to the HTML template.</p>
22+
{{> templates/src/widgets/code/code-snippet file=routes section=routes.sections.routes}}
23+
<p>Finally its hooked into our <a href="https://github.com/StubbornJava/StubbornJava/blob/master/stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/StubbornJavaWebApp.java#L58">router</a> and now we have a functioning <a href="/best-selling-html-css-themes-and-website-templates">HTML / CSS Theme Template</a> page.

0 commit comments

Comments
 (0)