Skip to content
Open
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
39 changes: 30 additions & 9 deletions src/zimscraperlib/rewriting/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,8 @@ def get_html_rewrite_context(tag: str, attrs: AttrsList) -> str:
return tag


def extract_base_href(content: str) -> str | None:
"""Extract base href value from HTML content

This is done in a specific function before real parsing / rewriting of any HTML
because we need this information before rewriting any link since we might have stuff
before the <base> tag in html head (e.g. <link> for favicons)
"""
soup = BeautifulSoup(content, features="lxml")
def base_href_from_soup(soup: BeautifulSoup) -> str | None:
"""Base href from a document that has already been parsed."""
if not soup.head:
return None
for base in soup.head.find_all("base"):
Expand All @@ -161,6 +155,28 @@ def extract_base_href(content: str) -> str | None:
return None


def title_from_soup(soup: BeautifulSoup) -> str:
"""Text of the first <title>, with character references decoded.

An empty first title stays empty. A later <title>, for example inside an inline
SVG, does not replace it. That matches document.title in a browser.
"""
title = soup.find("title")
if title is None:
return ""
return title.get_text().strip() # pyright: ignore[reportAttributeAccessIssue, reportUnknownMemberType]


def extract_base_href(content: str) -> str | None:
"""Extract base href value from HTML content

This is done in a specific function before real parsing / rewriting of any HTML
because we need this information before rewriting any link since we might have stuff
before the <base> tag in html head (e.g. <link> for favicons)
"""
return base_href_from_soup(BeautifulSoup(content, features="lxml"))


@cache
def _cached_signature(func: Callable[..., Any]) -> Signature:
"""Returns the signature of a given callable
Expand Down Expand Up @@ -208,7 +224,12 @@ def rewrite(self, content: str) -> RewritenHtml:
raise Exception("ouput should not already be set") # pragma: no cover
self.output = io.StringIO()

self.base_href = extract_base_href(content)
# One parse for the base href and the title. The HTMLParser below runs with
# convert_charrefs=False, so a title is delivered as separate data and entity
# pieces and only the text before the first '&' used to be kept.
soup = BeautifulSoup(content, features="lxml")
self.base_href = base_href_from_soup(soup)
self.title = title_from_soup(soup)
self.css_rewriter = CssRewriter(self.url_rewriter, self.base_href)
self.js_rewriter = JsRewriter(
url_rewriter=self.url_rewriter,
Expand Down
41 changes: 41 additions & 0 deletions tests/rewriting/test_html_rewriting.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,47 @@ def test_extract_title():
)


def _rewriter() -> HtmlRewriter:
return HtmlRewriter(
ArticleUrlRewriter(article_url=HttpUrl("https://www.example.com/page.html")),
None,
None,
None,
)


@pytest.mark.parametrize(
("html", "expected"),
[
(
"<html><head><title>Tom &amp; Jerry</title></head></html>",
"Tom & Jerry",
),
(
"<html><head><title>Rock &amp; Roll &#8211; My Blog</title></head></html>",
"Rock & Roll – My Blog",
),
(
"<html><head><title>L&#039;Illustre Maurin</title></head></html>",
"L'Illustre Maurin",
),
(
"<html><head><title> Tom &amp; Jerry </title></head></html>",
"Tom & Jerry",
),
(
"<html><head><title></title></head><body><svg><title>Icon</title></svg></body></html>",
"",
),
],
)
def test_title_keeps_text_after_character_references(html: str, expected: str):
rewritten = _rewriter().rewrite(html)
assert rewritten.title == expected
if "&amp;" in html:
assert "&amp;" in rewritten.content


def test_rewrite_attributes():
rewriter = HtmlRewriter(
ArticleUrlRewriter(
Expand Down