Extracting Text from HTML in Java with Jsoup: What Survives the Conversion
How jsoup turns HTML into plain text in Java: what text() keeps and drops, how to preserve line breaks and links, and where readability and accessibility suffer.
Turning HTML into plain text in Java usually means parsing the markup with jsoup and calling text(). This review looks at what that conversion keeps, what it discards, and when the result is fit for its intended use. It relies on jsoup's documented behavior and general HTML and Unicode principles. No benchmarks, version-specific test runs or measured results were supplied, so the expected outputs shown below follow from documented behavior and should be confirmed against the jsoup release you use.
Short verdict
Jsoup is a sound choice for converting HTML to text in Java when you need the words of a page in source order and do not need its structure. Its main benefit is that it is a real HTML parser: it tolerates malformed markup, decodes character entities and leaves out script and style contents, which avoids the classic failures of stripping tags with regular expressions. The decisive tradeoff is that text() flattens everything into one line. Paragraphs, headings, list items, table cells and line breaks collapse into single spaces, and link targets and image alt text disappear. If people will read the output, or if structure carries meaning, use a line-preserving traversal or keep a structured format instead. Jsoup also does not run JavaScript, so it cannot extract content that a page builds in the browser.
Flat plain text is the better output when:
- You are building a full-text search index or matching keywords.
- You need text for a classifier, summarizer or language-detection step.
- You are comparing, counting or deduplicating page content.
- The destination cannot render HTML and only needs a short snippet.
Keep markup, or a structured format such as Markdown, when:
- Readers need headings, lists or tables to follow the content.
- Link destinations or image descriptions matter.
- The text will be edited and re-published as a web page.
- The output must remain navigable with assistive technology.
The basic conversion
Add the jsoup library (group org.jsoup, artifact jsoup) using the current release listed in the project's release notes, then parse the markup and call text() on the document or on a specific element.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
String html = "<p>Fish & chips</p><p>Price:<b> low</b></p>"
+ "<script>track()</script>";
Document doc = Jsoup.parse(html);
String text = doc.text();
// expected: "Fish & chips Price: low"
Three things happen in that example. The entity & is decoded to a literal ampersand. The two paragraphs are joined by a single space, and the bold run merges into the surrounding sentence. The script body is left out because jsoup stores script and style contents as data nodes rather than text nodes, and text() collects only text.
Fetching text from a web address
Jsoup can also download a page and parse it in one step. The URL string is passed in as a variable here.
Document doc = Jsoup.connect(pageUrl)
.userAgent("my-text-extractor")
.get();
String title = doc.title();
String bodyText = doc.body().text();
get() performs the HTTP request and parses the response. Network failures surface as an IOException, and by default a non-success HTTP status raises an HttpStatusException unless you call ignoreHttpErrors(true). Calling text() on the whole document can include head content such as the title, so body().text() is the narrower choice for page content. Because no JavaScript runs, single-page applications and lazily loaded sections may return little or no text; for those you would need a browser-based tool. Check the site's terms and robots rules before fetching pages automatically.
Since text() drops link destinations, collect them separately if you need them. The abs: prefix resolves relative links against the page address, and returns an empty string when no absolute address can be formed.
for (Element link : doc.select("a[href]")) {
String label = link.text();
String target = link.attr("abs:href");
// store label and target together
}
What the conversion actually changes
It helps to separate changes to the stored characters from changes in presentation. Jsoup works on the source markup, not on the rendered page. The character-level changes it makes are limited: it decodes entities into the characters they stand for, collapses runs of spaces, tabs and newlines into single spaces, trims the ends, and inserts a separator at block boundaries and line breaks. It does not reverse, mirror, restyle or substitute characters. Handling of non-breaking spaces has differed between releases, so if downstream code splits on ordinary spaces, check whether U+00A0 comes through unchanged.
Everything that lives in markup rather than in text is removed:
- Tags and all attributes, including href, src, alt, title, lang and dir.
- Script and style contents, and HTML comments.
- Heading levels, list bullets and numbering.
- Table rows and columns; cells run together separated by spaces.
CSS presentation is ignored
Jsoup does not apply stylesheets, which has practical consequences. Text hidden with display:none or a visually-hidden class is still extracted. Text inserted by CSS through ::before or ::after does not appear, because it never existed in the markup. A text-transform: uppercase rule is not applied, so you get the source capitalization. Visual reordering through flexbox order, grid placement or absolute positioning is ignored; output follows the order of the document source. The same applies to a mirror effect such as transform: scaleX(-1): it flips only the rendering, the characters were never reversed, and the extracted text reads normally.
Right-to-left and bidirectional text
Extracted text is in logical order, the order in which characters are stored, not the order in which a browser displays them. Hebrew or Arabic text therefore comes out as stored, and the destination's bidirectional algorithm decides how it is displayed. Markup that influenced direction is lost: a bdo element with dir="rtl" around the word abc displays as cba in a browser, but the extracted text is abc. Mixed-direction snippets, such as an Arabic phrase followed by a number or a Latin product name, can therefore display in a different order once pasted elsewhere. If that matters, wrap such runs in Unicode isolate characters (U+2068 FIRST STRONG ISOLATE and U+2069 POP DIRECTIONAL ISOLATE) or keep the dir attribute in an HTML output.
Styled Unicode letters, combining marks and emoji
If a page uses so-called fancy fonts made from Unicode characters, such as mathematical bold or script letters, jsoup passes them through unchanged, because they are real characters rather than styling. To fold them back into ordinary letters, apply compatibility normalization after extraction.
import java.text.Normalizer;
String folded = Normalizer.normalize(text, Normalizer.Form.NFKC);
NFKC is not a targeted fix. It also converts full-width letters,ligatures and superscript digits, so x² becomes x2, which can change meaning in formulas or units. Apply it only where that loss is acceptable.
Combining marks and multi-code-point emoji, such as flags, skin-tone variants and joined family sequences, also pass through intact because jsoup does not reorder characters. The risk appears later: truncating extracted text with substring() by char index can split a surrogate pair, separate a letter from its accent, or break an emoji sequence into fragments. Cut at grapheme boundaries instead, for example with the regular expression construct \X or BreakIterator.getCharacterInstance(). Older JDK releases handled some emoji sequences less completely, so test with the kinds of characters your pages contain.
Preserving line breaks and paragraphs
wholeText() keeps whitespace, but it is the whitespace of the HTML source file, not of the visual layout. It can include indentation from the markup and still miss breaks where the source has none, and its treatment of br has varied between releases. For readable output, a small traversal that emits a newline after block elements and line breaks gives more predictable control.
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
static String toReadableText(Element root) {
StringBuilder sb = new StringBuilder();
NodeTraversor.traverse(new NodeVisitor() {
@Override
public void head(Node node, int depth) {
if (node instanceof TextNode) {
sb.append(((TextNode) node).text());
} else if (node.nodeName().equals("li")) {
sb.append("- ");
}
}
@Override
public void tail(Node node, int depth) {
boolean block = node instanceof Element && ((Element) node).isBlock();
if (block || node.nodeName().equals("br")) {
sb.append('\n');
}
}
}, root);
return sb.toString()
.replaceAll(" *\n *", "\n")
.replaceAll("\n{3,}", "\n\n")
.strip();
}
Called on doc.body() for the input <h1>Menu</h1><ul><li>Soup</li><li>Bread</li></ul><p>Line one<br>Line two</p>, the logic of this visitor should produce the lines shown below. Run it against your own jsoup version to confirm. Note that isBlock() reflects jsoup's built-in tag table, not CSS, so a span styled as display:block will not start a new line.
Menu
- Soup
- Bread
Line one
Line two
Choosing an extraction method
| Method | What you get | Best for |
| text() | Normalized single-line text, entities decoded, scripts excluded | Indexing, matching, snippets |
| wholeText() | Text with source-file whitespace kept | Preformatted content, debugging |
| ownText() | Only the element's direct text, without children | Pulling a specific field |
| Jsoup.clean(html, Safelist.none()) | Tags removed, but output is still HTML-escaped | Sanitizing before showing as HTML, not plain-text export |
| Custom NodeVisitor | Your own rules for breaks, bullets and links | Human-readable output |
The clean() route is a common source of confusion. Its output is an HTML fragment, so an ampersand comes back as &. Treating that as plain text shows readers literal entity codes. Safelist replaced the older Whitelist class, so older examples may use the previous name.
Readability and usability after copying or sharing
Plain text pastes predictably into most editors and messaging tools because there is no formatting to lose. The single-line output of text() is hard to read in an email, document or ticket, however, so use the line-preserving approach whenever people rather than programs will read the result.
Extraction removes the semantics that assistive technology relies on: heading navigation, list item counts, table header associations, link purpose, image alt text and the lang attribute that guides screen reader pronunciation. If extracted text is offered as the readable version of a page, it will be harder to navigate than the original, so provide structured HTML or Markdown as well. This review did not test any specific screen reader or destination application; these points follow from what the conversion removes, not from observed behavior in a named tool.
Because reading order follows the source and CSS is ignored, output can include material a sighted visitor never sees: skip links, visually hidden labels, cookie notices, menus and footers. For search indexing this boilerplate dilutes relevance, and hidden text may misrepresent the page. Removing known noise before extraction helps, for example doc.select("nav, footer, [hidden]").remove(). Be deliberate about aria-hidden content, which is hidden from assistive technology but may still be meaningful to sighted readers.
Extraction is one-way. The resulting text cannot be mapped back to positions in the markup, so if content must be edited and re-rendered, edit the HTML instead. When extracted text is inserted into a web page again, escape it, for instance through a templating engine's automatic escaping or jsoup's Entities.escape(). Decoding turns <script> in the source into a literal <script>, and inserting that unescaped creates a cross-site scripting risk.
Gaps in this review
No measured results, performance data or version-specific tests were available. Details that have changed between jsoup releases, including the handling of br in wholeText() and of non-breaking spaces, should be checked against the release notes for the version you deploy. No compatibility testing with particular editors, messaging platforms, search engines or screen readers was supplied, so the usability points above describe likely effects of losing structure rather than confirmed outcomes in any one environment.