Sub topic 12
Detecting duplicate and near-duplicate content
This chapter assumes you have read the chapters on URL normalization and the seen set. It also assumes you can read short Python programs and know what a hash function is.
Why URLs are not enough
Normalization and the seen set stop you from fetching the same URL twice. They cannot see that two different URLs return the same page. Mirrors, print views, session IDs, and tracking parameters all produce this. Duplicates waste bandwidth and storage, and they skew anything built on the crawl, such as search rankings or word counts.
Content deduplication runs after the fetch. It compares what you downloaded against what you already have.
Exact duplicates: hash the content
Compute a fingerprint of the page text and keep the fingerprints in a set, just like seen URLs. If the fingerprint is already present, skip storing the page and skip extracting its links.
Hash the extracted text, not the raw bytes. Raw HTML often differs in small ways, such as a timestamp, a nonce in a script tag, or whitespace. Lowercasing and collapsing whitespace before hashing removes some of this noise.
Near duplicates: shingles and simhash
Two pages that differ by one line, such as a changed date or a different ad, have different SHA-256 hashes. A near-duplicate check needs a fingerprint where similar texts get similar values.
Simhash does this in three steps:
- Split the text into shingles, which are overlapping runs of k consecutive words.
- Hash each shingle to 64 bits. For each bit position, add 1 if the bit is set and subtract 1 if not.
- Set each output bit to 1 if its total is positive.
Similar texts share most shingles, so most bit totals keep the same sign. The Hamming distance, the number of differing bits, between two simhashes is then small. A common cutoff for 64-bit fingerprints is a distance of about 3 or less.
import hashlib
import re
def tokens(text):
return re.findall(r'\w+', text.lower())
def exact_fingerprint(text):
normalized = ' '.join(tokens(text))
return hashlib.sha256(normalized.encode('utf-8')).hexdigest()
def simhash(text, k=3, bits=64):
words = tokens(text)
totals = [0] * bits
for i in range(max(1, len(words) - k + 1)):
shingle = ' '.join(words[i:i + k])
digest = hashlib.blake2b(shingle.encode('utf-8'), digest_size=bits // 8).digest()
h = int.from_bytes(digest, 'big')
for b in range(bits):
totals[b] += 1 if (h >> b) & 1 else -1
value = 0
for b in range(bits):
if totals[b] > 0:
value |= 1 << b
return value
def distance(a, b):
return bin(a ^ b).count('1')
page_a = 'The crawler fetches pages, extracts links, and queues new URLs for later visits.'
page_b = 'The crawler fetches pages, extracts links, and queues new URLs for later visits today.'
page_c = 'Bread needs flour, water, salt, and yeast, then time to rise before baking.'
print(exact_fingerprint(page_a) == exact_fingerprint(page_b))
print(distance(simhash(page_a), simhash(page_b)))
print(distance(simhash(page_a), simhash(page_c)))The first comparison prints False, because one extra word changes the SHA-256 hash completely. The second distance is usually much smaller than the third. Unrelated texts tend to differ in about half the bits.
Common errors
- Hashing boilerplate. Menus, footers, and cookie banners are identical across a site, so every page looks similar. Extract the main content first when you can.
- Comparing against every stored simhash. That scan is O(n) per page. At scale, split each fingerprint into blocks and index them, so candidates must share a block exactly before you compute distances.
- Dropping links too early. A near-duplicate page may still link to new pages, such as a different page of a listing. Decide deliberately whether to follow its links.
- Short pages. With few shingles, one changed word moves the fingerprint a lot. Set a minimum length before you trust the distance.
Exercise
Two pages differ only in a visitor counter. Why does the exact SHA-256 check miss them, and which check catches them?
Show answer
Any change to the hashed text gives a completely different SHA-256 value, so the exact check sees two unrelated pages. A simhash comparison catches them. Almost all shingles match, so the fingerprints differ in only a few bits, which is under the distance threshold.