Java Web Scraping With Jsoup (Tested, 2026)
Runnable Java web scraping with Jsoup 1.23.2 - CSS selectors, pagination, login with CSRF tokens, JavaScript pages without a browser, and real timings.

On this page
Java gets waved off for scraping, which is odd: the JVM is already running half the backends that consume scraped data. Java web scraping has a low floor — one dependency, twenty lines — and jsoup has quietly fixed the thing everyone complains about. Everything here ran today on Java 21.0.13 and jsoup 1.23.2 against quotes.toscrape.com, a sandbox built for this exact purpose. I kept the timings: about 2 seconds for the baseline fetch, 10.7 for a polite 10-page crawl, and no browser process anywhere.
You get five working programs, one measured trap per section, and a rule for when to stop writing Java and open a real browser instead.
What you need
- A JDK, tested on Temurin 21.0.13; jsoup itself runs on Java 8 and up
- jsoup 1.23.2 (MIT license, zero runtime dependencies)
- Gson 2.15.0 (Apache-2.0) for one step: decoding JSON that ships inside a script tag
Maven:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.23.2</version>
</dependency>
Gradle: implementation 'org.jsoup:jsoup:1.23.2'
No build tool? I ran everything here as plain files, no pom.xml:
curl -sLO https://jsoup.org/packages/jsoup-1.23.2.jar
curl -sLO https://repo1.maven.org/maven2/com/google/code/gson/gson/2.15.0/gson-2.15.0.jar
javac -cp jsoup-1.23.2.jar:gson-2.15.0.jar Baseline.java
java -cp .:jsoup-1.23.2.jar Baseline
One note on the sandbox: quotes.toscrape.com publishes no robots.txt at all. I still pause 500 ms between requests to the same host, and you should on real sites; the etiquette lives in how to scrape without getting blocked, and the pause costs almost nothing.
The Java web scraping baseline: Jsoup.connect and CSS selectors
jsoup does both halves of the job: it fetches the URL and parses the HTML into a DOM you query with CSS selectors.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
public class Baseline {
public static void main(String[] args) throws IOException {
long t0 = System.nanoTime();
Document doc = Jsoup.connect("https://quotes.toscrape.com/")
.timeout(10_000)
.get();
long t1 = System.nanoTime();
var quotes = doc.select("div.quote");
System.out.println("quotes on page: " + quotes.size());
Element first = quotes.first();
System.out.println("text: " + first.select("span.text").text());
System.out.println("author: " + first.select("small.author").text());
System.out.println("tags: " + first.select("a.tag").eachText());
System.out.printf("fetch + parse: %.0f ms%n", (t1 - t0) / 1e6);
}
}
Output from today’s runs:
quotes on page: 10
text: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
author: Albert Einstein
tags: [change, deep-thoughts, thinking, world]
fetch + parse: 2007 ms (five samples: 1.9–2.1 s, first-ever run 3.4 s)
About that two seconds: almost all of it is network round-trips from my connection in Thailand to the site’s origin, not the JVM. The parse itself is single-digit milliseconds on a 12 KB page. If your baseline feels slow, measure before blaming Java; nanoTime around the fetch, like above, separates the wire from the work.
The selector vocabulary is the same one you’d use in a browser’s DevTools: div.quote, small.author, a.tag. If you need a refresher on how that tree works, the DOM page covers what you’re querying.
jsoup’s default User-Agent is a fake Chrome: change it
Older tutorials warn that Java scrapers announce themselves as Java/1.8.0_xxx. That stopped being true in jsoup 1.21.1 (June 2025, their issue #2341). I pointed today’s baseline at a local header-echo server, and jsoup 1.23.2 sent this with zero configuration:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36
That string is baked into the jar. Convenient for compatibility (Wikipedia served my fetch a 200 with and without a custom UA), but a strange default for you. Your crawler now shows up in site logs as a MacBook running Chrome, which makes debugging harder (yours is indistinguishable from real traffic) and is a quiet way to disrespect an operator who tried to filter bots. When a site’s terms allow scraping, say who you are:
Document doc = Jsoup.connect(url)
.userAgent("my-scraper/0.1 ([email protected])")
.get();
If a site blocks you even with a browser-identical UA, the filter is probably TLS-fingerprint based, and no header fixes that. You need a real browser or a tool with impersonation, not a header argument.
Pagination: follow rel="next" with absUrl
jsoup has no crawler. For a linear pagination, you don’t need one: read the next link, absolute-ify it, repeat:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.TreeSet;
public class Crawl {
public static void main(String[] args) throws IOException, InterruptedException {
long t0 = System.nanoTime();
String url = "https://quotes.toscrape.com/";
var authors = new TreeSet<String>();
int quotes = 0, pages = 0;
while (url != null) {
Document doc = Jsoup.connect(url).timeout(10_000).get();
pages++;
quotes += doc.select("div.quote").size();
doc.select("small.author").forEach(a -> authors.add(a.text()));
var next = doc.selectFirst("li.next > a");
url = (next == null) ? null : next.absUrl("href");
Thread.sleep(500); // politeness pause between requests to the same host
}
long t1 = System.nanoTime();
System.out.printf("pages: %d, quotes: %d, distinct authors: %d%n",
pages, quotes, authors.size());
System.out.printf("total: %.2f s (includes the 500 ms pause per page)%n", (t1 - t0) / 1e9);
}
}
pages: 10, quotes: 100, distinct authors: 50
total: 10.67 s (includes the 500 ms pause per page)
The absUrl("href") call is the part people get wrong. The sandbox’s next links are relative (/page/2/); absUrl resolves them against the document’s base URL. Build them by hand and you’ll 404 on the first hop. If pagination is deeper than next-links (category trees, filters, URL discovery), that’s a crawler’s job; the web crawler guide covers the queue-and-visited-set machinery.
Login forms: cookies and the CSRF token
quotes.toscrape.com’s login is a realistic form: a hidden csrf_token input, and a session cookie that the server binds to that token. jsoup handles it in three requests, and hides a trap on the second one.
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class Login {
public static void main(String[] args) throws IOException {
long t0 = System.nanoTime();
// 1. GET the form; the session cookie it sets is bound to the CSRF token.
Connection.Response form = Jsoup.connect("https://quotes.toscrape.com/login").execute();
String csrf = form.parse().selectFirst("input[name=csrf_token]").val();
// 2. POST credentials + token. Don't let jsoup follow the 302 itself:
// the followed body arrives with the pre-login cookie.
Connection.Response login = Jsoup.connect("https://quotes.toscrape.com/login")
.cookies(form.cookies())
.data("csrf_token", csrf, "username", "demo", "password", "demo")
.method(Connection.Method.POST)
.followRedirects(false)
.execute();
// 3. Carry the fresh session cookie to the next request yourself.
Document home = Jsoup.connect("https://quotes.toscrape.com/")
.cookies(login.cookies())
.get();
System.out.println("POST status: " + login.statusCode()
+ " -> " + login.header("Location"));
System.out.println("session cookie present: " + login.cookies().containsKey("session"));
System.out.println("'Logout' visible: " + (home.selectFirst("a:contains(Logout)") != null));
System.out.printf("login round-trips: %.0f ms%n", (System.nanoTime() - t0) / 1e6);
}
}
POST status: 302 -> /
session cookie present: true
'Logout' visible: true
login round-trips: 4166 ms
The trap, measured: with jsoup’s default redirect-following, the POST still succeeds and the response’s session cookie even contains your username. But the body jsoup hands you from the followed 302 was fetched with the pre-login cookie, so it renders the anonymous homepage. My first version printed 'Logout' visible: false with a 200 status and a logged-in cookie jar. The fix is followRedirects(false) plus carrying login.cookies() to the next request yourself. Once your session lives past one JVM run, persist the cookie map; the patterns are in scraping sites that require login.
JavaScript pages: decode the script tag before you open a browser
The sandbox’s /js/ variant renders its quotes client-side. The parser sees nothing:
div.quote elements: 0
Most tutorials jump from here to Selenium. Wait. View-source first: the quotes are sitting in an inline <script> as var data = [ ... ], a JSON array with text, author, Goodreads link, and tags for all ten quotes. That’s not a rendering problem, it’s a string-extraction problem:
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class JsPage {
public static void main(String[] args) throws IOException {
long t0 = System.nanoTime();
Document doc = Jsoup.connect("https://quotes.toscrape.com/js/").get();
// What a parser sees: the div.quote elements do not exist yet.
System.out.println("div.quote elements: " + doc.select("div.quote").size());
// The quotes live in an inline script: `var data = [ ... ];`
var script = doc.selectFirst("script:containsData(var data)");
String json = script.html().replaceAll("(?s)^.*?var\\s+data\\s*=\\s*(\\[.*?\\]);.*$", "$1");
JsonArray arr = JsonParser.parseString(json).getAsJsonArray();
var quotes = new Gson().fromJson(arr, Quote[].class);
System.out.println("decoded quotes: " + quotes.length);
System.out.println("first: " + quotes[0].text());
System.out.println("by: " + quotes[0].author().name());
System.out.printf("fetch + decode: %.0f ms%n", (System.nanoTime() - t0) / 1e6);
}
record Quote(String text, Author author, String[] tags) {
record Author(String name) {}
}
}
div.quote elements: 0
decoded quotes: 10
first: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
by: Albert Einstein
fetch + decode: 2515 ms (cold JVM, includes the network fetch)
The regex cuts everything outside the array: the assignment’s prefix and the render loop that follows it. No browser process, no WebDriver download, and the whole run stays in the low thousands of milliseconds. The general decision tree (check view-source and the Network tab before anything else) is in how to scrape dynamic websites.
When the data genuinely isn’t in the HTML, then you open a browser. The Java options:
| Library | Runs JS | Cost per page | Use when |
|---|---|---|---|
| jsoup 1.23.2 | No | ~2 s fetch, ms parse (measured) | Static HTML or data embedded in scripts |
| HtmlUnit 4.x | Partial (Rhino) | Lighter than a full browser | Tolerable-JS pages, no browser install |
| Selenium 4.x + ChromeDriver | Yes | Seconds + a browser process | Existing Selenium suites, legacy support |
| Playwright for Java | Yes | Seconds + one-time browser download | Modern alternative, better waits than Selenium |
I measured none of the bottom three today; those numbers are typical magnitudes, not receipts. What I will say from experience: a browser render is always the slow path, and client-side vs server-side rendering decides which path you’re on before you write a line.
Validate your extraction before selectors rot
Every selector in this tutorial is a promise the site can break. div.quote works until a redesign renames the div, and no compiler will catch it; Java’s type safety stops at Document.select(), which happily returns an empty list. So validate the shape, and fail loudly:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Validate {
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("https://quotes.toscrape.com/").get();
List<String> problems = new ArrayList<>();
var quotes = doc.select("div.quote");
if (quotes.size() != 10) {
problems.add("expected 10 quotes per page, got " + quotes.size());
}
var seen = new HashSet<String>();
for (Element q : quotes) {
String text = q.selectFirst("span.text") == null ? "" : q.selectFirst("span.text").text();
String author = q.selectFirst("small.author") == null ? "" : q.selectFirst("small.author").text();
if (text.isBlank()) problems.add("quote with empty text");
if (author.isBlank()) problems.add("quote with empty author");
if (q.select("a.tag").isEmpty()) problems.add("quote without tags: " + text);
if (!seen.add(text)) problems.add("duplicate quote: " + text);
}
if (!problems.isEmpty()) {
problems.forEach(p -> System.out.println("FAIL: " + p));
System.exit(1);
}
System.out.println("OK: " + quotes.size() + " quotes, all with text, author, tags; no duplicates");
}
}
Today’s runs, healthy and then after a simulated redesign:
OK: 10 quotes, all with text, author, tags; no duplicates (exit 0)
FAIL: expected 10 quotes per page, got 0 (exit 1)
The failure line is what the selectors changed to article.quote under me — the exact break a real redesign produces. Exit code 1 is the point: an empty dataset should wake someone up, not quietly export a CSV of nothing. If you maintain scrapers across dozens of sites, self-healing scrapers re-synthesize broken selectors instead of just reporting them.
When to skip Java entirely
If the scraping is a means to an end, writing a fifth Jsoup.connect wrapper is a cost, not a craft. For comparison, one command with Magpie (a Go CLI, AGPL/commercial dual license) returned the same homepage as clean Markdown in 2.06 s when I ran this sandbox for the Go version of this tutorial: boilerplate stripped, quotes and author links intact. Its limit showed up the same day: the JavaScript page above hits its thin-page quality gate and returns nothing. Write Java when the scraping logic is the product; run a tool when the data is.
FAQ
Is Java good for web scraping? For static pages, yes: one 537 KB jar, fast parsing, and the JVM your team already runs. JavaScript-rendered sites need a browser driver, which costs seconds per page and a browser process.
Does jsoup run JavaScript? No. It parses the HTML that arrives. Check whether the data ships inside a script tag first; decoding embedded JSON is milliseconds. Otherwise use Playwright or Selenium.
jsoup or Selenium — which one? Decide per page, not per project: jsoup for any HTML that arrives complete, a browser only where the payload needs rendering. Selenium if you’re extending an existing suite; Playwright for Java for new browser work.
Is web scraping with Java legal? It depends on the data, the site’s terms, and your jurisdiction; this isn’t legal advice. Public pages, robots.txt, and published APIs are the safe ground; scraping behind login walls you don’t own is not.
Why does my jsoup login show the logged-out page?
jsoup’s redirect-following refetches the 302 target with the pre-login cookie. Turn redirects off, take login.cookies() from the POST response, and send them on the next request yourself.
The baseline program above is twenty lines — run it against a page you actually need, and print one field end to end before you design anything. The day your script grows a second cookie jar or a third retry loop, that’s the tool-shaped signal; and if there’s no logic worth keeping at all, Node.js and Go run the same sandbox walkthroughs if another runtime fits your stack better.


