mirror of
https://github.com/ArchiveBox/ArchiveBox.git
synced 2025-05-13 14:44:29 -04:00
feat: add og:title metadata as alternative title
This commit is contained in:
parent
c35d5e6b41
commit
eda3836dee
1 changed files with 30 additions and 7 deletions
|
@ -1,6 +1,7 @@
|
||||||
__package__ = 'archivebox.extractors'
|
__package__ = 'archivebox.extractors'
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
from html.parser import HTMLParser
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
@ -23,11 +24,32 @@ from ..config import (
|
||||||
from ..logging_util import TimedProgress
|
from ..logging_util import TimedProgress
|
||||||
|
|
||||||
|
|
||||||
HTML_TITLE_REGEX = re.compile(
|
class TitleParser(HTMLParser):
|
||||||
r'<title.*?>' # start matching text after <title> tag
|
def __init__(self, *args, **kwargs):
|
||||||
r'(.[^<>]+)', # get everything up to these symbols
|
super().__init__(*args, **kwargs)
|
||||||
re.IGNORECASE | re.MULTILINE | re.DOTALL | re.UNICODE,
|
self.title_tag = ""
|
||||||
)
|
self.title_og = ""
|
||||||
|
self.inside_title_tag = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def title(self):
|
||||||
|
return self.title_tag or self.title_og or None
|
||||||
|
|
||||||
|
def handle_starttag(self, tag, attrs):
|
||||||
|
if tag.lower() == "title" and not self.title_tag:
|
||||||
|
self.inside_title_tag = True
|
||||||
|
elif tag.lower() == "meta" and not self.title_og:
|
||||||
|
attrs = dict(attrs)
|
||||||
|
if attrs.get("property") == "og:title" and attrs.get("content"):
|
||||||
|
self.title_og = attrs.get("content")
|
||||||
|
|
||||||
|
def handle_data(self, data):
|
||||||
|
if self.inside_title_tag and data:
|
||||||
|
self.title_tag += data.strip()
|
||||||
|
|
||||||
|
def handle_endtag(self, tag):
|
||||||
|
if tag.lower() == "title":
|
||||||
|
self.inside_title_tag = False
|
||||||
|
|
||||||
|
|
||||||
@enforce_types
|
@enforce_types
|
||||||
|
@ -63,8 +85,9 @@ def save_title(link: Link, out_dir: Optional[Path]=None, timeout: int=TIMEOUT) -
|
||||||
timer = TimedProgress(timeout, prefix=' ')
|
timer = TimedProgress(timeout, prefix=' ')
|
||||||
try:
|
try:
|
||||||
html = download_url(link.url, timeout=timeout)
|
html = download_url(link.url, timeout=timeout)
|
||||||
match = re.search(HTML_TITLE_REGEX, html)
|
parser = TitleParser()
|
||||||
output = htmldecode(match.group(1).strip()) if match else None
|
parser.feed(html)
|
||||||
|
output = parser.title
|
||||||
if output:
|
if output:
|
||||||
if not link.title or len(output) >= len(link.title):
|
if not link.title or len(output) >= len(link.title):
|
||||||
Snapshot.objects.filter(url=link.url, timestamp=link.timestamp).update(title=output)
|
Snapshot.objects.filter(url=link.url, timestamp=link.timestamp).update(title=output)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue