Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ convert
A list of tags to convert. This option can't be used with the
``strip`` option.

decompose
A list of tags to remove together with their contents. Their descendants
are not converted. Defaults to ``None``. For example,
``markdownify(html, decompose=['aside', 'noscript'])`` removes those entire
subtrees. This takes precedence over ``strip`` and ``convert`` and does not
modify a supplied BeautifulSoup object. Unlike ``decompose``, ``strip``
disables tag conversion while keeping the converted child content.
``script`` and ``style`` contents are already removed by default; putting
those tags in ``strip`` disables that default conversion.

autolinks
A boolean indicating whether the "automatic link" style should be used when
a ``a`` tag's contents match its href. Defaults to ``True``.
Expand Down
5 changes: 5 additions & 0 deletions markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ class DefaultOptions:
code_language = ''
code_language_callback = None
convert = None
decompose = None
default_title = False
escape_asterisks = True
escape_underscores = True
Expand Down Expand Up @@ -233,6 +234,10 @@ def process_element(self, node, parent_tags=None):
return self.process_tag(node, parent_tags=parent_tags)

def process_tag(self, node, parent_tags=None):
# Skip the entire subtree without mutating the supplied soup.
if node.name in (self.options['decompose'] or []):
return ''

# For the top-level element, initialize the parent context with an empty set.
if parent_tags is None:
parent_tags = set()
Expand Down
2 changes: 2 additions & 0 deletions markdownify/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ def main(argv=sys.argv[1:]):
parser.add_argument('-a', '--autolinks', action='store_true',
help="A boolean indicating whether the 'automatic link' style "
"should be used when a 'a' tag's contents match its href.")
parser.add_argument('--decompose', nargs='*',
help="A list of tags to remove together with their contents.")
parser.add_argument('--default-title', action='store_false',
help="A boolean to enable setting the title of a link to its "
"href, if no title is given.")
Expand Down
42 changes: 42 additions & 0 deletions tests/test_decompose.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import io

from bs4 import BeautifulSoup

from markdownify import MarkdownConverter, markdownify
from markdownify.main import main


def test_decompose_suppresses_content_and_descendant_converters():
class GuardConverter(MarkdownConverter):
def convert_b(self, el, text, parent_tags):
raise AssertionError('Excluded subtree was visited')

html = '<p>Hello</p><aside><b>Noise</b></aside><p>World</p>'
assert GuardConverter(decompose=['aside']).convert(html) == 'Hello\n\nWorld'


def test_decompose_takes_precedence_over_strip_and_convert():
html = '<script>alert(1)</script><noscript>Noise</noscript><p>Keep</p>'
assert markdownify(html, decompose=['script', 'noscript'], strip=['script']) == 'Keep'
assert markdownify(html, decompose=['noscript'], convert=['p']) == 'alert(1)\n\nKeep\n\n'


def test_decompose_works_with_root_tags_without_mutating_soup():
soup = BeautifulSoup('<aside><p>Noise</p></aside>', 'html.parser')
original = str(soup)
converter = MarkdownConverter(decompose=['aside'])
assert converter.convert_soup(soup.aside) == ''
assert str(soup) == original


def test_decompose_preserves_default_and_inline_boundaries():
html = '<p>before <span>noise</span> after</p>'
assert markdownify(html) == 'before noise after'
assert markdownify(html, decompose=[]) == 'before noise after'
assert markdownify(html, decompose=['span']) == 'before after'


def test_decompose_cli(monkeypatch, capsys):
monkeypatch.setattr('sys.stdin', io.StringIO('<p>Keep</p><aside>Noise</aside>'))
main(['--decompose', 'aside'])
assert capsys.readouterr().out == 'Keep\n'