Skip to main content
SeleniumDecoded

Find Broken Links on a Page

Collect every link on a page in one script call, check each URL with a fast HTTP HEAD request in parallel, and report 4xx and 5xx responses with their text.

Stable Verified against Selenium 4.52.0

Problem

A content-heavy site has hundreds of links per page. Some point to removed pages or typo’d URLs. Clicking each link with Selenium would take minutes and test nothing the HTTP status code does not already tell you.

Solution

Use Selenium for what only a browser can do: render the page and give you the final, absolute href of every link (including ones added by JavaScript). Then check the URLs with a plain HTTP client, in parallel, using HEAD and falling back to GET when servers reject HEAD.

Collect links in the browser, check them over HTTP
Selenium 3 & 4 Stable
import java.net.URI;
import java.net.http.*;
import java.util.concurrent.*;
// One round trip: a.href is already absolute
@SuppressWarnings("unchecked")
List<String> urls = (List<String>) ((JavascriptExecutor) driver).executeScript("""
return [...new Set([...document.querySelectorAll('a[href]')]
.map(a => a.href)
.filter(h => h.startsWith('http')))];
""");
HttpClient http = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.executor(Executors.newFixedThreadPool(10))
.build();
Map<String, Integer> broken = new ConcurrentHashMap<>();
CompletableFuture.allOf(urls.stream().map(url ->
http.sendAsync(HttpRequest.newBuilder(URI.create(url)).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.discarding())
.thenCompose(r -> r.statusCode() == 405 || r.statusCode() == 403
? http.sendAsync(HttpRequest.newBuilder(URI.create(url)).GET().build(), HttpResponse.BodyHandlers.discarding())
: CompletableFuture.completedFuture(r))
.thenAccept(r -> { if (r.statusCode() >= 400) broken.put(url, r.statusCode()); })
.exceptionally(e -> { broken.put(url, -1); return null; })
).toArray(CompletableFuture[]::new)).join();
assertTrue(broken.isEmpty(), "Broken links: " + broken);
from concurrent.futures import ThreadPoolExecutor
import requests
urls = driver.execute_script("""
return [...new Set([...document.querySelectorAll('a[href]')]
.map(a => a.href)
.filter(h => h.startsWith('http')))];
""")
session = requests.Session()
session.headers["User-Agent"] = driver.execute_script("return navigator.userAgent")
def check(url):
try:
r = session.head(url, allow_redirects=True, timeout=10)
if r.status_code in (403, 405):
r = session.get(url, allow_redirects=True, timeout=10, stream=True)
return url, r.status_code
except requests.RequestException:
return url, -1
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(check, urls))
broken = {u: s for u, s in results if s == -1 or s >= 400}
assert not broken, f"Broken links: {broken}"
const urls = await driver.executeScript(`
return [...new Set([...document.querySelectorAll('a[href]')]
.map(a => a.href)
.filter(h => h.startsWith('http')))];`);
async function check(url) {
try {
let r = await fetch(url, { method: 'HEAD', redirect: 'follow', signal: AbortSignal.timeout(10000) });
if (r.status === 403 || r.status === 405) {
r = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(10000) });
}
return [url, r.status];
} catch {
return [url, -1];
}
}
// Simple batching keeps concurrency at 10
const results = [];
for (let i = 0; i < urls.length; i += 10) {
results.push(...(await Promise.all(urls.slice(i, i + 10).map(check))));
}
const broken = results.filter(([, s]) => s === -1 || s >= 400);
assert.deepStrictEqual(broken, [], `Broken links: ${JSON.stringify(broken)}`);
var urls = ((IReadOnlyCollection<object>)((IJavaScriptExecutor)driver).ExecuteScript("""
return [...new Set([...document.querySelectorAll('a[href]')]
.map(a => a.href)
.filter(h => h.startsWith('http')))];
""")).Cast<string>().ToList();
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
using var gate = new SemaphoreSlim(10);
async Task<(string Url, int Status)> Check(string url)
{
await gate.WaitAsync();
try
{
var r = await http.SendAsync(new HttpRequestMessage(HttpMethod.Head, url));
if ((int)r.StatusCode is 403 or 405)
r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
return (url, (int)r.StatusCode);
}
catch (Exception) { return (url, -1); }
finally { gate.Release(); }
}
var results = await Task.WhenAll(urls.Select(Check));
var broken = results.Where(r => r.Status == -1 || r.Status >= 400).ToList();
Assert.That(broken, Is.Empty, "Broken links: " + string.Join(", ", broken));

Why It Works

a.href (the DOM property, not the attribute) returns the resolved absolute URL, so relative links, <base> tags and links injected by JavaScript all come out ready to request. Collecting them in a single executeScript call avoids one WebDriver round trip per link. HEAD asks only for headers, so checks are fast and cheap for the server; the GET fallback handles servers and CDNs that reject or mishandle HEAD. Bounded parallelism keeps the run short without hammering the site.

Gotchas

  • Rate limits and bot protection. External sites (and some CDNs) answer automated requests with 403 or 429. Send a browser-like User-Agent (the Python example copies the browser’s), keep concurrency low, and consider checking only internal links in CI.
  • Authenticated pages. Links behind login return 302 to the login page or 401. Copy the browser’s session cookie into the HTTP client (see Log In via the API for the reverse direction).
  • Skip what is not HTTP. The filter drops mailto:, tel: and javascript: links. Also consider skipping #fragment-only links and known flaky external domains.
  • Soft 404s. Some sites return 200 with a “page not found” body. If that matters, GET internal links and assert on a marker in the HTML.
  • Images and scripts too. Extend the selector to img[src], script[src] and link[href] to catch missing assets; use the src / href properties for absolute URLs.
  • Run it as a separate smoke check, not inside every functional test. Link health and user journeys fail for different reasons and deserve different owners.

Learn the theory