diff --git a/src/zimscraperlib/rewriting/html.py b/src/zimscraperlib/rewriting/html.py
index 35247d46..764b5a5d 100644
--- a/src/zimscraperlib/rewriting/html.py
+++ b/src/zimscraperlib/rewriting/html.py
@@ -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 tag in html head (e.g. 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"):
@@ -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
, with character references decoded.
+
+ An empty first title stays empty. A later , 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 tag in html head (e.g. 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
@@ -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,
diff --git a/tests/rewriting/test_html_rewriting.py b/tests/rewriting/test_html_rewriting.py
index 71df415e..d91d9c72 100644
--- a/tests/rewriting/test_html_rewriting.py
+++ b/tests/rewriting/test_html_rewriting.py
@@ -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"),
+ [
+ (
+ "Tom & Jerry",
+ "Tom & Jerry",
+ ),
+ (
+ "Rock & Roll – My Blog",
+ "Rock & Roll – My Blog",
+ ),
+ (
+ "L'Illustre Maurin",
+ "L'Illustre Maurin",
+ ),
+ (
+ " Tom & Jerry ",
+ "Tom & Jerry",
+ ),
+ (
+ "",
+ "",
+ ),
+ ],
+)
+def test_title_keeps_text_after_character_references(html: str, expected: str):
+ rewritten = _rewriter().rewrite(html)
+ assert rewritten.title == expected
+ if "&" in html:
+ assert "&" in rewritten.content
+
+
def test_rewrite_attributes():
rewriter = HtmlRewriter(
ArticleUrlRewriter(