From bd4c46d0e9483e0552a5eb4f2560b4b49eb95d5f Mon Sep 17 00:00:00 2001 From: Fess-AKA-DeadMonk Date: Fri, 12 Jul 2024 20:09:19 +0300 Subject: [PATCH 1/2] fixed the way the converter is chosen for tags with names containing symbols not suitable for python def html tags may contain symbols like `:` and `-` which are not suitable for the python function names simple name converter allows usage of the methods for tags like `tag:subtag-name` --- markdownify/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/markdownify/__init__.py b/markdownify/__init__.py index 2360210..8e90a61 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -172,7 +172,8 @@ def process_tag(self, node, convert_as_inline, children_only=False): text = text_strip + newlines + next_text_strip if not children_only: - convert_fn = getattr(self, 'convert_%s' % node.name, None) + fn_name = 'convert_%s' % node.name.translate(''.maketrans(':-', '__')) + convert_fn = getattr(self, fn_name, None) if convert_fn and self.should_convert_tag(node.name): text = convert_fn(node, text, convert_as_inline) From febb5ef9513d21e2ed5773663796e6bc602e72ae Mon Sep 17 00:00:00 2001 From: chrispy Date: Sun, 19 Jan 2025 09:40:14 -0500 Subject: [PATCH 2/2] add unit tests Signed-off-by: chrispy --- tests/test_custom_converter.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/tests/test_custom_converter.py b/tests/test_custom_converter.py index a3e33ac..adc83f7 100644 --- a/tests/test_custom_converter.py +++ b/tests/test_custom_converter.py @@ -2,22 +2,29 @@ from bs4 import BeautifulSoup -class ImageBlockConverter(MarkdownConverter): +class UnitTestConverter(MarkdownConverter): """ - Create a custom MarkdownConverter that adds two newlines after an image + Create a custom MarkdownConverter for unit tests """ def convert_img(self, el, text, convert_as_inline): + """Add two newlines after an image""" return super().convert_img(el, text, convert_as_inline) + '\n\n' + def convert_custom_tag(self, el, text, convert_as_inline): + """Ensure conversion function is found for tags with special characters in name""" + return "FUNCTION USED: %s" % text -def test_img(): + +def test_custom_conversion_functions(): # Create shorthand method for conversion def md(html, **options): - return ImageBlockConverter(**options).convert(html) + return UnitTestConverter(**options).convert(html) assert md('Alt text') == '![Alt text](/path/to/img.jpg "Optional title")\n\n' assert md('Alt text') == '![Alt text](/path/to/img.jpg)\n\n' + assert md("text") == "FUNCTION USED: text" + def test_soup(): html = 'test'