Skip to content

Commit

Permalink
Optionally pass the Beautiful Soup object to constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
biolds committed Sep 25, 2024
1 parent f2fadcb commit c4b76c5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
18 changes: 12 additions & 6 deletions linkpreview/linkpreview.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from os.path import dirname

from bs4 import BeautifulSoup

from linkpreview.link import Link
from linkpreview.preview import (
Generic,
Expand All @@ -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):
Expand Down
7 changes: 5 additions & 2 deletions linkpreview/preview/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit c4b76c5

Please sign in to comment.