Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Much of the site is generated from Google Sheets and Docs, and the generated fil

Run both against a build (`hugo -d <dir>`), as `deploy.yaml` does:

- `python3 scripts/check_seo_html.py <dir>`. Add a regression check here when you fix a template.
- `python3 scripts/check_seo_html.py <dir>`. When you fix a template, add a regression check as a new module in `scripts/seo_checks/` (a docstring and `check(site)`), with tests in `scripts/tests/test_seo_<module>.py`; the runner finds it, so no shared file changes.
Comment thread
LukasWallrich marked this conversation as resolved.
Resolved
- `python3 scripts/check_sitemap_lastmod.py <dir>/sitemap.xml [--compare-source]` (needs full Git history).

Unit tests: `python3 -m unittest discover -s scripts/tests` and `python3 -m unittest discover -s scripts -p 'test_parse_disciplines_gdoc.py'`; `script-tests.yaml` runs both on every PR.
2 changes: 1 addition & 1 deletion content/resources/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def wrangle_data(df):

# Titles and abstracts pasted from publisher pages can carry HTML entities such as
# "&ldquo;". Hugo escapes the "&" again, so pages showed "&ldquo;" as text and the
# meta description failed check 10 of scripts/check_seo_html.py. Only complete
# meta description failed scripts/seo_checks/description_entities.py. Only complete
# entities ending in ";" are decoded, so a bare "&" stays as it is, and a name is
# decoded only if the whole name is an HTML entity. "<" and ">" stay encoded:
# abstracts are rendered as Markdown with raw HTML allowed, so decoding them
Expand Down
4 changes: 2 additions & 2 deletions layouts/sitemap.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{{/* Override of Hugo's built-in sitemap template, kept deliberately close to it
so it stays easy to diff against upstream. It leaves out author profiles that
custom_head.html marks noindex (same condition there), so the sitemap never
lists a page it asks search engines not to index (check 14 in
scripts/check_seo_html.py). It also appends data/external_sitemap.yaml. */ -}}
lists a page it asks search engines not to index
(scripts/seo_checks/sitemap_noindex.py). It also appends data/external_sitemap.yaml. */ -}}
{{ printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
{{- range .Pages }}
Expand Down
1,310 changes: 53 additions & 1,257 deletions scripts/check_seo_html.py

Large diffs are not rendered by default.

Empty file added scripts/seo_checks/__init__.py
Empty file.
315 changes: 315 additions & 0 deletions scripts/seo_checks/_site.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,315 @@
"""The parsed build that every check in this folder receives.

`load_site(public_dir)` reads each index.html under the build once. A check's
`check(site)` uses `site.pages` (one `Page` per index.html, sorted by path),
`site.home` (the homepage's `Page`, or None) and `site.public_dir`.
"""

import os
import re
from html.parser import HTMLParser
from urllib.parse import unquote, urlparse

SOURCE_URL_TOKEN = re.compile(r'https?://[^\s<>"]+')


class PageParser(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.h1_texts = []
self.urls = []
self.imgs = []
self.card_pictures = []
self._whole_card_picture = None
self.meta = {}
self.code_classes = []
self.metas = []
self._in_pre = False
self._h1_depth = 0
self._h1_buffer = []
self.jsonld = []
self.canonical = None
self.title = ""
self.resource_links = []
self._in_title = False
self._in_resource_heading = False
self.gloss_terms = []
self._jsonld_buffer = None
self.largest_inline_script = 0
self._inline_script = None
self.ids = set()
self.references = set()
self.reference_sources = []
self._ref_source = None
self.citations = []
self.crumb_links = []
self._in_crumbs = False
self.alternates = []
self.related_links = []
self._related_tag = None # the element holding a term page's related terms (section.term-related)
self.takeaway_links = []
self._in_takeaways = False
self.anchors = []
self.h1_english_texts = [] # text of the elements marked lang="en" inside an <h1>
self._h1_english_tag = None
self.empty_network_icons = False
self._network_icon_items = None

def _finish_ref_source(self):
if self._ref_source is not None:
self.reference_sources.append(self._ref_source)
self._ref_source = None

def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "li":
self._finish_ref_source()
if self._network_icon_items is not None:
self._network_icon_items += 1
if tag == "ul":
ul_classes = (attrs.get("class") or "").split()
if "summary-takeaways" in ul_classes:
self._in_takeaways = True
if "network-icon" in ul_classes:
self._network_icon_items = 0
if tag == "a" and self._in_takeaways:
self.takeaway_links.append(attrs.get("href") or "")
if tag == "div":
classes = (attrs.get("class") or "").split()
self._whole_card_picture = "ec-thumb-whole" in classes if "ac-thumb" in classes else None
if tag == "script" and not attrs.get("src"):
self._inline_script = 0
if attrs.get("id"):
self.ids.add(attrs["id"])
if attrs.get("data-reference"):
self.references.add(attrs["data-reference"])
if attrs.get("data-source"):
if tag == "li":
self._ref_source = (attrs["data-source"], [])
else:
self.reference_sources.append((attrs["data-source"], []))
if tag == "a" and self._ref_source is not None and attrs.get("href"):
self._ref_source[1].append(attrs["href"])
if tag == "nav" and "crumbs" in (attrs.get("class") or "").split():
self._in_crumbs = True
if tag == "link" and attrs.get("rel") == "alternate" and attrs.get("hreflang") and attrs.get("href"):
self.alternates.append(attrs["href"])
if self._related_tag is None and "term-related" in (attrs.get("class") or "").split():
self._related_tag = tag
if tag == "a" and self._related_tag:
self.related_links.append(attrs.get("href") or "")
if tag == "a" and self._in_crumbs:
self.crumb_links.append(attrs.get("href") or "")
if tag == "a" and "cite" in (attrs.get("class") or "").split():
self.citations.append((attrs.get("href") or "", attrs.get("data-cite") or ""))
if tag == "script" and attrs.get("type") == "application/ld+json":
self._jsonld_buffer = []
elif tag == "link" and attrs.get("rel") == "canonical":
self.canonical = attrs.get("href")
if tag == "title":
self._in_title = True
if tag == "h2" and "res-title" in (attrs.get("class") or "").split():
self._in_resource_heading = True
if tag == "a" and self._in_resource_heading and attrs.get("href"):
self.resource_links.append(attrs["href"])
# The English part of a translated term's heading: <bdi lang="en"> in Doors, <span lang="en"> on main.
if self._h1_depth and self._h1_english_tag is None and attrs.get("lang") == "en":
self._h1_english_tag = tag
self.h1_english_texts.append("")
if tag == "a" and attrs.get("href"):
self.anchors.append(attrs["href"])
if tag == "h1":
self._h1_depth += 1
elif tag in ("script", "link"):
url = attrs.get("src") or attrs.get("href")
if url:
self.urls.append(url)
elif tag == "img":
self.imgs.append(attrs)
if self._whole_card_picture is not None and attrs.get("src"):
folder = urlparse(attrs["src"]).path.rpartition("/")[0]
self.card_pictures.append((folder, self._whole_card_picture))
elif tag == "a" and "gloss-term" in (attrs.get("class") or "").split():
self.gloss_terms.append(attrs.get("href") or "")
elif tag == "meta":
self.metas.append(attrs)
key = attrs.get("property") or attrs.get("name")
if key and key not in self.meta:
self.meta[key] = attrs.get("content") or ""
elif tag == "pre":
self._in_pre = True
elif tag == "code" and self._in_pre:
self.code_classes.append(attrs.get("class") or "")

def handle_endtag(self, tag):
if tag == self._h1_english_tag:
self.h1_english_texts[-1] = self.h1_english_texts[-1].strip()
self._h1_english_tag = None
if tag in ("li", "ul"):
self._finish_ref_source()
if tag == "div":
self._whole_card_picture = None
if tag == "ul":
self._in_takeaways = False
if self._network_icon_items is not None:
if self._network_icon_items == 0:
self.empty_network_icons = True
self._network_icon_items = None
if tag == "nav":
self._in_crumbs = False
if tag == self._related_tag:
self._related_tag = None
if tag == "script" and self._inline_script is not None:
self.largest_inline_script = max(self.largest_inline_script, self._inline_script)
self._inline_script = None
if tag == "script" and self._jsonld_buffer is not None:
self.jsonld.append("".join(self._jsonld_buffer))
self._jsonld_buffer = None
if tag == "title":
self._in_title = False
if tag == "h2":
self._in_resource_heading = False
if tag == "pre":
self._in_pre = False
if tag == "h1" and self._h1_depth > 0:
self._h1_depth -= 1
if self._h1_depth == 0:
self.h1_texts.append("".join(self._h1_buffer).strip())
self._h1_buffer = []

def close(self):
super().close()
self._finish_ref_source()
# A script left open at the end of the file still counts.
if self._inline_script is not None:
self.largest_inline_script = max(self.largest_inline_script, self._inline_script)
self._inline_script = None

def handle_data(self, data):
if self._ref_source is not None:
self._ref_source[1].extend(m.group(0) for m in SOURCE_URL_TOKEN.finditer(data))
if self._in_title:
self.title += data
if self._inline_script is not None:
self._inline_script += len(data.encode("utf-8"))
if self._jsonld_buffer is not None:
self._jsonld_buffer.append(data)
if self._h1_depth > 0:
self._h1_buffer.append(data)
if self._h1_english_tag is not None:
self.h1_english_texts[-1] += data


class Page:
def __init__(self, path, parser):
self.path = path
self.h1_texts = parser.h1_texts
self.title = parser.title.strip()
self.resource_links = parser.resource_links
self.urls = parser.urls
self.imgs = parser.imgs
self.card_pictures = parser.card_pictures
self.meta = parser.meta
self.code_blocks = [cls.split() for cls in parser.code_classes]
self.descriptions = [m.get("content") or "" for m in parser.metas
if (m.get("name") or "").lower() == "description"]
robots = " ".join((m.get("content") or "").lower() for m in parser.metas
if (m.get("name") or "").lower() == "robots")
self.refreshes = [m.get("content") or "" for m in parser.metas
if (m.get("http-equiv") or "").lower() == "refresh"]
url_path = "/" + os.path.dirname(path).replace(os.sep, "/")
self.url_path = url_path.rstrip("/") + "/"
elsewhere = (parser.canonical is not None and
unquote(urlparse(parser.canonical).path) != unquote(self.url_path))
# Redirect stubs, noindexed pages and pages canonicalised to another URL
# never reach search results as such.
self.noindex = "noindex" in robots
self.indexable = not self.noindex and not self.refreshes and not elsewhere
self.jsonld = parser.jsonld
self.canonical = parser.canonical
self.largest_inline_script = parser.largest_inline_script
self.ids = parser.ids
self.references = parser.references
self.reference_sources = parser.reference_sources
self.citations = parser.citations
self.gloss_terms = parser.gloss_terms
self.crumb_links = parser.crumb_links
self.alternates = parser.alternates
self.related_links = parser.related_links
self.takeaway_links = parser.takeaway_links
self.anchors = parser.anchors
self.h1_english_texts = parser.h1_english_texts
self.empty_network_icons = parser.empty_network_icons

def loads(self, needle):
return any(needle in url for url in self.urls)

@property
def has_highlight_code(self):
return any("hljs" not in cls and "language-mermaid" not in cls
for cls in self.code_blocks)

@property
def has_mermaid_code(self):
return any("language-mermaid" in cls for cls in self.code_blocks)

@property
def imgs_without_alt(self):
return [img for img in self.imgs if "alt" not in img]

@property
def imgs_without_dims(self):
return [img for img in self.imgs
if "width" not in img or "height" not in img]


def load_pages(public_dir):
pages = []
for root, _dirs, files in os.walk(public_dir):
for name in files:
if name != "index.html":
continue
full = os.path.join(root, name)
parser = PageParser()
with open(full, encoding="utf-8", errors="replace") as handle:
parser.feed(handle.read())
parser.close()
pages.append(Page(os.path.relpath(full, public_dir), parser))
pages.sort(key=lambda page: page.path)
return pages


class Site:
def __init__(self, public_dir, pages):
self.public_dir = public_dir
self.pages = pages
self.home = next((p for p in pages if p.path == "index.html"), None)


def load_site(public_dir):
return Site(public_dir, load_pages(public_dir))


def page_from_html(text, path="index.html"):
"""One parsed page, for tests."""
parser = PageParser()
parser.feed(text)
parser.close()
return Page(path, parser)


SHARE_IMAGE_EXTS = (".png", ".jpg", ".jpeg")


def is_share_format(url):
"""X and LinkedIn show previews for PNG and JPEG share images, not WebP (#870)."""
return url.split("?")[0].lower().endswith(SHARE_IMAGE_EXTS)


# A preview build serves the site under a prefix (e.g. /rebrand-doors/); glossary URLs are compared from /glossary/ on.
GLOSSARY_URL_PATH = re.compile(r"/glossary/.*$")


def glossary_url_key(href):
match = GLOSSARY_URL_PATH.search(unquote(urlparse(href).path))
return match.group(0) if match else None
Loading
Loading