HTML to Markdown with html2text



我可以使用 html2text 库成功地将一些 HTML 代码转换为 python 中的 markdown,它看起来像这样:

def mark_down_formatting(html_text, url):
h = html2text.HTML2Text()
# Options to transform URL into absolute links
h.body_width = 0
h.protect_links = True
h.wrap_links = False
h.baseurl = url
md_text = h.handle(html_text)
return md_text

这有一段时间很好,但它有限制,因为我找不到任何方法来自定义文档的输出。

实际上我不需要很多自定义,我只需要这个HTML标签<span class="searched_found">example text</span>在markdown中转换为我给出的任何内容。可能是这个+example text+

所以我正在寻找解决我的问题的方法,也因为 html2text 是一个很好的库,它允许我配置一些选项,比如我用超链接显示的选项,有一个基于这个库的解决方案会很好。

更新:

我有一个使用 BeautifulSoup 库的解决方案,但我认为它是一个临时补丁,因为它添加了另一个依赖项并增加了许多不必要的处理。我在这里所做的是在解析为 markdown之前编辑 HTML:

def processing_to_markdown(html_text, url, delimiter):
# Not using "lxml" parser since I get to see a lot of different HTML
# and the "lxml" parser tend to drop content when parsing very big HTML
# that has some errors inside
soup = BeautifulSoup(html_text, "html.parser")
# Finds all <span class="searched_found">...</span> tags
for tag in soup.findAll('span', class_="searched_found"):
tag.string = delimiter + tag.string + delimiter
tag.unwrap()  # Removes the tags to only keep the text
html_text = unicode(soup)
return mark_down_formatting(html_text, url)

对于很长的HTML内容,这被证明是相当慢的,因为我们解析HTML两次,一次使用BeautifulSoup,然后使用html2text。

markdownify可以提供帮助

markdownify 使用 BeautifulSoup 进行解析

soup = BeautifulSoup(html, 'html.parser')

转换可以定制

import markdownify
"""
https://stackoverflow.com/questions/45034227/html-to-markdown-with-html2text
https://beautiful-soup-4.readthedocs.io/en/latest/#multi-valued-attributes
https://beautiful-soup-4.readthedocs.io/en/latest/#contents-and-children
"""
class CustomMarkdownConverter(markdownify.MarkdownConverter):
def convert_a(self, el, text, convert_as_inline):
classList = el.get("class")
if classList and "searched_found" in classList:
# custom transformation
# unwrap child nodes of <a class="searched_found">
text = ""
for child in el.children:
text += super().process_tag(child, convert_as_inline)
return text
# default transformation
return super().convert_a(el, text, convert_as_inline)
# Create shorthand method for conversion
def md4html(html, **options):
return CustomMarkdownConverter(**options).convert(html)
md = md4html("""<a class="searched_found"><b>hello</b> world</a>""")

最新更新