generic_html.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. __package__ = 'archivebox.parsers'
  2. import re
  3. from typing import IO, Iterable, Optional
  4. from datetime import datetime
  5. from django.db.models import Model
  6. from ..util import (
  7. htmldecode,
  8. enforce_types,
  9. URL_REGEX,
  10. )
  11. from html.parser import HTMLParser
  12. from urllib.parse import urljoin
  13. class HrefParser(HTMLParser):
  14. def __init__(self):
  15. super().__init__()
  16. self.urls = []
  17. def handle_starttag(self, tag, attrs):
  18. if tag == "a":
  19. for attr, value in attrs:
  20. if attr == "href":
  21. self.urls.append(value)
  22. @enforce_types
  23. def parse_generic_html_export(html_file: IO[str], root_url: Optional[str]=None, **_kwargs) -> Iterable[Model]:
  24. """Parse Generic HTML for href tags and use only the url (support for title coming later)"""
  25. from core.models import Snapshot
  26. html_file.seek(0)
  27. for line in html_file:
  28. parser = HrefParser()
  29. # example line
  30. # <li><a href="http://example.com/ time_added="1478739709" tags="tag1,tag2">example title</a></li>
  31. parser.feed(line)
  32. for url in parser.urls:
  33. if root_url:
  34. # resolve relative urls /home.html -> https://example.com/home.html
  35. url = urljoin(root_url, url)
  36. for archivable_url in re.findall(URL_REGEX, url):
  37. yield Snapshot(
  38. url=htmldecode(archivable_url),
  39. timestamp=str(datetime.now().timestamp()),
  40. title=None,
  41. #tags=None,
  42. #sources=[html_file.name],
  43. )