Merge pull request 'fix(news): unwrap CDATA titles at ingest and on /api/news' (#62) from wt/t_4f334c8b into master
Some checks failed
build-and-deploy / build-push-deploy (push) Failing after 6s
Some checks failed
build-and-deploy / build-push-deploy (push) Failing after 6s
Reviewed-on: #62
This commit is contained in:
commit
7c77aa3103
6 changed files with 154 additions and 1 deletions
|
|
@ -3,6 +3,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import re
|
||||
from email.utils import parsedate_to_datetime
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
|
@ -30,3 +31,26 @@ def article_timestamp(pub_date: str | None) -> datetime.datetime:
|
|||
except ValueError:
|
||||
pass
|
||||
return datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
|
||||
# Whole-title CDATA wrapper only. Keep in sync with app/news_title.py —
|
||||
# the scraper image and the API image do not share a package.
|
||||
_CDATA_WRAPPER = re.compile(
|
||||
r"\A\s*<!\[CDATA\[(.*?)\]\]>\s*\Z",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def unwrap_cdata_title(title):
|
||||
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
|
||||
|
||||
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
|
||||
``Hello``. Real HTML (``<b>Hello</b>``) and a title that merely contains
|
||||
the markers are returned as-is. Non-strings pass through.
|
||||
"""
|
||||
if not isinstance(title, str):
|
||||
return title
|
||||
match = _CDATA_WRAPPER.match(title)
|
||||
if match is None:
|
||||
return title
|
||||
return match.group(1).strip()
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ import psycopg2
|
|||
import os
|
||||
from scrapy.exceptions import DropItem
|
||||
|
||||
from newsScraper.feed_util import unwrap_cdata_title
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Feed items dated further ahead than this are event listings (or clock skew
|
||||
|
|
@ -104,6 +106,7 @@ class PostgresPipeline:
|
|||
if url in self.seen_urls:
|
||||
raise DropItem(f"Duplicate URL (in-memory): {url}")
|
||||
self.seen_urls.add(url)
|
||||
item['title'] = unwrap_cdata_title(item['title'])
|
||||
try:
|
||||
self.cur.execute("""
|
||||
INSERT INTO articles (title, url, content, domain, timestamp)
|
||||
|
|
|
|||
Loading…
Reference in a new issue