From c4b76c5102d2e74163f38e7b51ea6ea6c4b1935e Mon Sep 17 00:00:00 2001 From: Laurent Defert Date: Fri, 26 Jul 2024 17:00:14 +0200 Subject: [PATCH] Optionally pass the Beautiful Soup object to constructors --- linkpreview/linkpreview.py | 18 ++++++++++++------ linkpreview/preview/base.py | 7 +++++-- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/linkpreview/linkpreview.py b/linkpreview/linkpreview.py index e6f17e8..7005680 100644 --- a/linkpreview/linkpreview.py +++ b/linkpreview/linkpreview.py @@ -1,5 +1,7 @@ from os.path import dirname +from bs4 import BeautifulSoup + from linkpreview.link import Link from linkpreview.preview import ( Generic, @@ -14,13 +16,17 @@ class LinkPreview: - def __init__(self, link: Link, parser: str = PARSER): + def __init__(self, link: Link, parser: str | None = PARSER, soup: BeautifulSoup | None = None): + if parser and soup: + raise Exception( + 'Only one of `parser` or soup` argument must be provided to LinkPreview') + self.link = link - self.generic = Generic(link, parser) - self.opengraph = OpenGraph(link, parser) - self.twitter = TwitterCard(link, parser) - self.microdata = Microdata(link, parser) - self.jsonld = JsonLd(link, parser) + self.generic = Generic(link, parser, soup) + self.opengraph = OpenGraph(link, parser, soup) + self.twitter = TwitterCard(link, parser, soup) + self.microdata = Microdata(link, parser, soup) + self.jsonld = JsonLd(link, parser, soup) @LazyAttribute def sources(self): diff --git a/linkpreview/preview/base.py b/linkpreview/preview/base.py index 108df63..3681285 100644 --- a/linkpreview/preview/base.py +++ b/linkpreview/preview/base.py @@ -7,9 +7,12 @@ class PreviewBase(object): # pragma: nocover Base for all web preview. """ - def __init__(self, link: Link, parser: str): + def __init__(self, link: Link, parser: str, soup: BeautifulSoup): self.link = link - self._soup = BeautifulSoup(self.link.content, parser) + if soup: + self._soup = soup + else: + self._soup = BeautifulSoup(self.link.content, parser) @property def title(self):