Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Using jsoup, fetch nothing remotely but parse an HTML string, extract all links with their absolute URLs from <a> tags inside div.article, and explain how base URLs work.

We parse the string with Jsoup.parse(html, baseUri), where the second argument is the URL the page is assumed to come from, then select the links with doc.select("div.article a[href]") and read each one with link.attr("abs:href") or link.absUrl("href"). jsoup resolves every relative href against the base URI the same way a browser does, so ../about becomes a full https URL.

Why this question is asked

Extracting links from HTML is a common task in crawlers, link checkers, content migration tools and tests that verify rendered pages. The interesting part of this question is not the selector but the base URL: a page full of relative links such as /contact or ../img/logo.png is useless to us until we know which page they were relative to. Interviewers ask it to see whether we understand how browsers resolve URLs and whether we know jsoup well enough to let it do the work. In this answer, we will recap what jsoup is, write the extraction code, look closely at how base URIs and relative links are resolved, and see how jsoup handles messy HTML and text.

1A Quick Recap of jsoup

jsoup is a Java library that parses HTML into a document tree, the same kind of tree a browser builds, which we call the DOM (Document Object Model). Each tag becomes an Element, and we can find elements with CSS selectors, the same selector syntax we use in style sheets: div.article means a div with the class article, a[href] means an a tag that has an href attribute, and a space between them means 'somewhere inside'.

jsoup can also fetch pages over HTTP with Jsoup.connect(url).get(), but the question asks us to parse a string we already have. That is the better habit anyway, because it keeps parsing separate from network access and makes the code easy to test.

2Extracting the Links From div.article

Here is the complete extraction. The HTML has links inside and outside the article, relative and absolute, and one link without an href.

Java
String html = """
<div class="nav"><a href="/home">Home</a></div>
<div class="article">
<p>Read <a href="part-2.html">part two</a> and
<a href="/about">about us</a>,
or <a href="https://other.org/x">elsewhere</a>.</p>
<a name="top">anchor without href</a>
</div>
""";
Document doc = Jsoup.parse(html, "https://example.org/blog/");
Elements links = doc.select("div.article a[href]");
for (Element link : links) {
System.out.println(link.text() + " -> " + link.attr("abs:href"));
}
// part two -> https://example.org/blog/part-2.html
// about us -> https://example.org/about
// elsewhere -> https://other.org/x
System.out.println(links.size()); // 3: the nav link and the anchor without href are not selected

Notice what the selector did. The Home link is in div.nav, so it is not inside div.article and is skipped. The anchor without an href is inside the article, but a[href] only matches a tags that have the attribute, so it is skipped too. We get exactly the three links we wanted.

The prefix abs: in attr("abs:href") asks jsoup to return the attribute resolved to an absolute URL. link.absUrl("href") does the same thing and reads a little more clearly. If the value cannot be resolved, for example a relative link with no base URI, both return an empty string, not null, so we can filter with isEmpty().

3How the Base URI Resolves Relative Links

The second argument to Jsoup.parse() is the base URI: the address we tell jsoup the document came from. jsoup cannot know it from a plain string, so if we leave it out, relative links have nothing to resolve against and abs:href returns an empty string. When jsoup fetches a page itself with connect().get(), it sets the base URI to the final URL after redirects.

Resolution follows the same rules as a browser, which are defined in the URL standard. A link that starts with a scheme such as https: is already absolute and is returned unchanged. A link that starts with / replaces the whole path and keeps the scheme and host. A plain relative link such as part-2.html replaces only the last segment of the base path, which is why the trailing slash in https://example.org/blog/ matters so much. And ../ moves one level up.

Java
Document d1 = Jsoup.parse("<a href='part-2.html'>x</a>", "https://example.org/blog/");
d1.selectFirst("a").absUrl("href"); // https://example.org/blog/part-2.html
Document d2 = Jsoup.parse("<a href='part-2.html'>x</a>", "https://example.org/blog");
d2.selectFirst("a").absUrl("href"); // https://example.org/part-2.html (no trailing slash: "blog" is a file name)
Document d3 = Jsoup.parse("<a href='../img/a.png'>x</a>", "https://example.org/blog/2026/");
d3.selectFirst("a").absUrl("href"); // https://example.org/blog/img/a.png
Document d4 = Jsoup.parse("<a href='part-2.html'>x</a>");
d4.selectFirst("a").absUrl("href"); // "" (empty: no base URI to resolve against)
How relative hrefs resolve against https://example.org/blog/
href in the pageRuleAbsolute URL
https://other.org/xalready absolute, unchangedhttps://other.org/x
/aboutreplaces the whole pathhttps://example.org/about
part-2.htmlreplaces the last path segmenthttps://example.org/blog/part-2.html
../img/a.pnggoes up one level firsthttps://example.org/img/a.png
?page=2keeps the path, replaces the queryhttps://example.org/blog/?page=2
#topkeeps everything, adds a fragmenthttps://example.org/blog/#top
The trailing slash in the base decides whether blog is treated as a folder or as a file.

There is one more source of the base: the HTML itself. If the document contains a <base href="..."> tag in its head, browsers resolve relative links against it instead of the page address, and jsoup does the same, so the base URI we pass is overridden by the page's own base tag. This is worth knowing when results look wrong: check whether the page declares its own base.

4Messy HTML and Text Extraction

Real pages are rarely clean. Tags are left open, paragraphs are nested wrongly and attributes lack quotes. jsoup follows the HTML parsing rules browsers use, so it repairs the document the way a browser would instead of throwing an error the way an XML parser would.

Java
Document messy = Jsoup.parse("<div class=article><p>One <a href=/a>link<p>Two", "https://example.org/");
System.out.println(messy.select("div.article p").size()); // 2: the open <p> is closed by the next <p>
System.out.println(messy.selectFirst("a").absUrl("href")); // https://example.org/a
Element p = Jsoup.parse("<p> Hello\n\n <b>world</b> </p>").selectFirst("p");
System.out.println("[" + p.text() + "]"); // [Hello world]: whitespace normalised

element.text() returns the visible text of an element and its children, with runs of whitespace collapsed to single spaces and the ends trimmed, which is what we want for link labels. If we need the text exactly as written, wholeText() keeps the original whitespace.

5When We Do Fetch Pages

The question says to fetch nothing, and in tests that is right. In a real crawler we would fetch with Jsoup.connect(url).userAgent(...).timeout(...).get() or with our own HTTP client and then parse the body. Either way, scraping someone else's site comes with obligations: read its robots rules and terms of use, identify the client honestly, limit the request rate so we do not load the site, and cache what we have already fetched. Separating the fetch from the parse, as we did here, also makes those controls easier to put in one place.

6Follow-up questions

What is the difference between attr("href") and absUrl("href")?

attr("href") returns the attribute exactly as written in the HTML, which may be a relative path such as part-2.html. absUrl("href") and attr("abs:href") return the value resolved against the document's base URI, or an empty string when it cannot be resolved.

How would you make every link in the document absolute before saving it?

Select all elements with an href, then set each attribute to its absolute form, for example for (Element e : doc.select("[href]")) e.attr("href", e.absUrl("href")); and the same for [src]. Then doc.outerHtml() gives HTML that still works after it is moved to another location.

Can I use the same code to remove duplicate links?

Yes. Collect the absolute URLs into a LinkedHashSet, which drops duplicates and keeps the order they appeared. Comparing absolute URLs is important here, because /about and ../about may be the same page once resolved.

7Conclusion

In this answer, we parsed an HTML string with Jsoup.parse(html, baseUri), selected the links with the CSS selector div.article a[href], and read absolute URLs with abs:href or absUrl(). We saw that the base URI is what relative links resolve against, that its trailing slash matters, that a <base> tag in the page overrides it, and that without any base jsoup returns an empty string. We also saw that jsoup repairs broken HTML like a browser, that text() normalises whitespace, and that fetching real pages brings politeness rules with it.

What to say in the interviewAbout 70 seconds aloud

Open with

I would parse the string with Jsoup.parse, passing the HTML and a base URI, for example https://example.org/blog/. The base URI is the address the document is treated as coming from, and jsoup needs it because a plain string has no address.

Then, if they want more

Then I select with doc.select of div.article a[href], which finds a tags that have an href anywhere inside a div with the class article, and for each one I call absUrl of href, or attr with the abs: prefix, to get the absolute URL.

Resolution follows browser rules: an absolute link is unchanged, a link starting with a slash keeps only the scheme and host, and a plain relative link replaces the last path segment, so the trailing slash on the base matters.

If the page has its own base tag, that wins, and if there is no base at all absUrl returns an empty string. jsoup also tolerates malformed HTML the way browsers do, and text gives me the link label with whitespace normalised. If I did fetch pages with Jsoup.connect, I would respect robots rules, terms and rate limits.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using jsoup, fetch nothing remotely but parse an HTML string, extract all links with...": https://scrivio-interview-library.netlify.app/java/xml-processing/2737c325b7/