Skip to content

Commit 0a1343a

Browse files
committed
allow BeautifulSoup objects to be converted
1 parent 9d0b839 commit 0a1343a

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

README.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,18 @@ Options may be specified as kwargs to the ``markdownify`` function, or as a
110110
nested ``Options`` class in ``MarkdownConverter`` subclasses.
111111

112112

113+
Converting BeautifulSoup objects
114+
================================
115+
116+
.. code:: python
117+
118+
from markdownify import MarkdownConverter
119+
120+
# Create shorthand method for conversion
121+
def md(soup, **options):
122+
return ImageBlockConverter(**options).convert_soup(soup)
123+
124+
113125
Creating Custom Converters
114126
==========================
115127

markdownify/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,9 @@ def __init__(self, **options):
9696

9797
def convert(self, html):
9898
soup = BeautifulSoup(html, 'html.parser')
99+
return self.convert_soup(soup)
100+
101+
def convert_soup(self, soup):
99102
return self.process_tag(soup, convert_as_inline=False, children_only=True)
100103

101104
def process_tag(self, node, convert_as_inline, children_only=False):

tests/test_custom_converter.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from markdownify import MarkdownConverter
2+
from bs4 import BeautifulSoup
23

34

45
class ImageBlockConverter(MarkdownConverter):
@@ -16,3 +17,9 @@ def md(html, **options):
1617

1718
assert md('<img src="/path/to/img.jpg" alt="Alt text" title="Optional title" />') == '![Alt text](/path/to/img.jpg "Optional title")\n\n'
1819
assert md('<img src="/path/to/img.jpg" alt="Alt text" />') == '![Alt text](/path/to/img.jpg)\n\n'
20+
21+
22+
def test_soup():
23+
html = '<b>test</b>'
24+
soup = BeautifulSoup(html, 'html.parser')
25+
assert MarkdownConverter().convert_soup(soup) == '**test**'

0 commit comments

Comments
 (0)