"""Reproduce the canonical example with Python 3.9+. All inputs are synthetic. Runs offline."""
import argparse
from email.message import Message
from html.parser import HTMLParser
import json
import re
from urllib.parse import urljoin, urlsplit
from xml.etree import ElementTree
def result(key, method, columns, rows, limits):
return dict(key=key, method=method, columns=columns, rows=rows, limits=limits)
class Links(HTMLParser):
def __init__(self):
super().__init__()
self.anchors, self.canonicals = [], []
self.in_head = False
def handle_starttag(self, tag, attrs):
attr = dict(attrs)
if tag == 'head':
self.in_head = True
if tag == 'a' and attr.get('href'):
self.anchors.append(attr['href'])
if self.in_head and tag == 'link' and 'canonical' in attr.get('rel','').lower().split() and attr.get('href'):
self.canonicals.append(attr['href'])
def handle_endtag(self, tag):
if tag == 'head':
self.in_head = False
def canonical():
base = 'https://shop.example/'
ns = 'http://www.sitemaps.org/schemas/sitemap/0.9'
rows = []
for html_path, header_path, map_path in [('a','a','a'),('a','b','a'),('a','a','b'),('b','a','b')]:
links = Links()
links.feed(f'
')
headers = Message()
headers['Link'] = f'<{base}{header_path}>; rel="canonical"'
xml = f'{base}{map_path}'
sitemap = ElementTree.fromstring(xml).findtext(f'{{{ns}}}url/{{{ns}}}loc')
target = re.fullmatch(r'<([^>]+)>; rel="canonical"', headers['Link'])[1]
signals = [links.canonicals[0],target,sitemap]
rows.append([urlsplit(url).path for url in signals])
return result('canonical',
'Assume /a and /b are equivalent product URLs on shop.example. Inspect four independent '
'configurations for /a. Parse its HTML head, read its synthetic HTTP Link header and '
'parse the single URL listed for this product in the XML sitemap. Report the three paths '
'on the same HTTPS origin. All three fields are extracted independently.',
['HTML canonical', 'HTTP canonical', 'Sitemap URL'], rows,
'A sitemap entry is not a canonical declaration and the three columns are not votes of '
'equal weight. The parser handles only these simple fixtures. No redirects, rendered '
'HTML, internal links or search engine selections are measured. Agreement cannot '
'guarantee which URL will be indexed. Disagreement alone does not establish a fault.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('case', nargs='?', choices=['canonical'])
parser.parse_args()
print(json.dumps(canonical(), indent=2, ensure_ascii=False))