Sub topic 6
Finding exact duplicates with content hashes
This chapter assumes you can read a crawl export (URL, status code, canonical, word count, body text) and filter and group rows in pandas. It also assumes you know how redirects and canonical tags work. Earlier chapters covered URL normalization and boilerplate removal. Here you use both to find pages whose extracted text is identical.
What an exact duplicate means in a crawl
An exact duplicate is a pair or group of URLs whose extracted main content is the same after cleanup. The raw HTML is rarely byte-identical. Pages carry timestamps, session IDs, tracking scripts and different canonical tags. So you compare text, not markup.
A content hash is a fixed-length fingerprint computed from text. The same input always produces the same hash. A one-character change produces a completely different hash. This makes hashing a fast way to find identical text. You compute one short string per page and group rows that share it. You never compare every page with every other page.
The result tells you which URLs are interchangeable in content. It does not tell you whether that is a problem. That depends on how the site already handles the group, which later chapters cover.
Choosing what to hash
What you hash decides what you find. Three common choices give three different answers.
| Input | Finds | Misses |
|---|---|---|
| Full HTML source | Byte-identical files | Almost everything, because of timestamps, nonces and canonical tags |
| All visible text | Pages with the same text, including menus and footers | Pages with the same article but different navigation or related-link blocks |
| Main content only | Pages with the same body, ignoring templates | Pages where boilerplate extraction failed or removed too much |
Hashing all visible text is easy but unreliable. Two pages with different "related products" blocks will hash differently even if the description is the same. Hashing main content is the better choice when your crawler can extract it. Use a content-area selector or an extraction rule you have checked on a sample of pages.
Be careful with extraction failures. If a rule returns an empty string for many pages, they all hash to the same value. You then see a huge "duplicate" group that is really an extraction bug. The script below guards against this.
Normalizing text before hashing
Normalization removes differences that carry no meaning. The script in this chapter applies three steps:
- Collapse runs of whitespace, including newlines and tabs, into single spaces.
- Lowercase the text.
- Strip leading and trailing spaces.
You can add more rules when your data needs them. Examples are removing a "Last updated" line, dropping a date stamp, or removing digits that only count visitors. Each rule widens what counts as a duplicate, so keep a note of every rule you add. If you cannot explain a rule to a client, do not use it.
Hashing and grouping in pandas
The script below reads a crawl export, keeps only pages that returned status 200, hashes the cleaned body text, and lists groups of URLs that share a hash.
import hashlib
import pandas as pd
df = pd.read_csv("crawl.csv") # columns: url, status, body_text, word_count
df = df[df["status"] == 200].copy()
def content_hash(text):
cleaned = " ".join(str(text).split()).lower()
return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()
df["body_hash"] = df["body_text"].fillna("").map(content_hash)
groups = df.groupby("body_hash")["url"].agg(list)
duplicates = groups[groups.str.len() > 1]
print(duplicates)Each step has a reason.
- Filter to status 200. Redirects (3xx) and errors (4xx, 5xx) have no meaningful body. Including them would group unrelated error pages together. Redirects are handled separately, because they are already a fix.
- Split and join on whitespace.
str.split()with no argument splits on any run of whitespace. Joining with a single space gives one consistent form. - Encode as UTF-8.
hashlibhashes bytes, not strings. - Use SHA-256. MD5 would also work for this job, since nobody is attacking your crawl. SHA-256 is the safer default and costs little.
- Group by hash. The grouped result maps each hash to a list of URLs. Groups of one are unique pages, so you drop them.
Guard against empty and tiny bodies
Pages with an empty body all hash to the same value. Pages with a few words, like "Loading..." or "Page not found", also collide. These are not duplicate content in a useful sense. They are usually extraction failures or soft 404s, which you should treat as a separate problem. Add a guard before grouping:
import hashlib
import pandas as pd
df = pd.read_csv("crawl.csv") # columns: url, status, body_text, word_count
df = df[df["status"] == 200].copy()
def content_hash(text):
cleaned = " ".join(str(text).split()).lower()
return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()
df["body_hash"] = df["body_text"].fillna("").map(content_hash)
empty_hash = content_hash("")
empty_pages = df[df["body_hash"] == empty_hash]
print(f"Pages with empty body: {len(empty_pages)}")
df = df[df["body_hash"] != empty_hash]
df = df[df["word_count"] >= 20]
sizes = df.groupby("body_hash")["url"].transform("count")
dupes = df[sizes > 1].copy()
dupes["group_size"] = sizes[sizes > 1]
dupes = dupes.sort_values(["group_size", "body_hash", "url"], ascending=[False, True, True])
print(dupes[["body_hash", "group_size", "url"]].head(20))The cutoff of 20 words is an example, not a rule. Pick a value from your own data, and report the pages you dropped so the exclusion stays visible.
Reading the groups
A list of duplicate groups is a starting point. Look at the groups from the largest down, and ask what created each one. The cause usually falls into a few patterns.
- URL variants. The same page at
http://andhttps://, with and withoutwww, with and without a trailing slash, or in upper and lower case. Normalize URLs first (see the earlier chapter on normalization) and these often collapse. - Parameters. Sort orders, tracking codes and session IDs that return the same body.
- Template reuse. Many distinct products or locations that share one description. These can be real duplicates of content even when the URLs are unrelated.
- Printer, AMP or mobile versions. Parallel URLs for one page.
- Staging or alternate hosts. A test host or a CDN host that was crawled by accident.
Add a normalized URL column and compare group sizes before and after. If a group of six drops to a group of one after normalization, the six URLs differ only by variants. If it stays at six, the duplication is in the content itself or in the parameters.
import pandas as pd
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
TRACKING = {"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "gclid", "fbclid"}
def normalize(url):
parts = urlsplit(url)
host = parts.netloc.lower()
path = parts.path or "/"
if path != "/" and path.endswith("/"):
path = path.rstrip("/")
query = sorted((k, v) for k, v in parse_qsl(parts.query) if k not in TRACKING)
return urlunsplit(("https", host, path, urlencode(query), ""))
urls = pd.Series([
"http://Example.com/shoes/?utm_source=news",
"https://example.com/shoes",
"https://example.com/shoes/?gclid=abc",
])
print(urls.map(normalize).nunique())This prints 1, because all three URLs normalize to https://example.com/shoes. In a real analysis, apply normalize to the url column, then count unique normalized URLs per hash.
Failure modes and edge cases
Hashing is exact, so it is easy to over-trust and easy to under-use.
- False negatives from small differences. A changed price, a date or one extra sentence gives a different hash. Those pages need near-duplicate detection, covered in the next chapter.
- False positives from extraction bugs. Pages whose content was never captured look identical. JavaScript-rendered pages are the usual cause when you crawl without rendering. Compare a few pages in the browser before you trust a large group.
- False positives from short content. Short legitimate pages, such as a "Contact us" line repeated on location pages, can match by chance. Check word count and template.
- Case and punctuation. Lowercasing is usually safe for English. Some languages and some content, such as code snippets, are case-sensitive in meaning. Know your site.
- Language versions. The same text on
/en/and/en-gb/pages is a legitimate pair when hreflang tags link them. Check hreflang before you call it a problem. - Encoding. Text from different crawl runs may differ in Unicode form, for example an accented letter stored as one character or as two. If you suspect this, apply
unicodedata.normalize("NFC", text)before hashing.
From groups to decisions
For each group, record four facts before you move on: the number of URLs, the likely cause, whether those URLs have canonical tags that agree with each other, and which URL gets the most internal links and organic traffic. These facts feed the clustering and remediation chapters. One pattern helps here: when every URL in a group has a canonical tag pointing to the same target, the site has already told search engines which URL to prefer. Treat those groups as lower priority than groups where each URL canonicalizes to itself.
A canonical link element in the head of a duplicate page names the preferred URL:
<link rel="canonical" href="https://example.com/shoes/">Search engines treat this as a hint, not a command. Compare it with redirects, internal links and sitemap entries. If those disagree with the canonical tag, the signal is weaker.
Exercise
Your hash grouping returns one group of 1,800 URLs. All have status 200, and almost all have a word count of 0. What is the most likely explanation, and what do you do before reporting it as a duplicate content problem?
Show answer
The body extraction most likely failed for these pages, for example because the content is rendered by JavaScript and the crawl did not render it. Empty text hashes to the same value for every page, so they group together. Check a few pages in a browser, re-crawl with rendering or fix the extraction rule, then re-run the hashing. Excluding the empty-body hash and low word counts, as in the guard script, keeps this group out of the real duplicate list.
Exercise
Two URLs, https://example.com/shoes and https://example.com/shoes/?sort=price, have the same body hash. A third, https://example.com/shoes/?sort=price&page=2, has a different hash. What does each result tell you?
Show answer
The first two share main content, so the sort parameter does not change the text. They are an exact duplicate pair, likely caused by a parameter URL. The third has a different hash because page 2 lists different products. It is a distinct page in a paginated series and not an exact duplicate of the first. You would still check its canonical and robots signals, but hashing correctly separates it from the first two.