【发布时间】:2017-12-15 11:56:06
【问题描述】:
我可以使用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
这有一段时间很好,但它有限制,因为我找不到任何方法来自定义 documentation 上的输出。
其实我不需要太多的定制,我只需要这个HTML标签<span class="searched_found">example text</span>在markdown中转换成我给的任何东西。可能是这个+example text+
所以我正在寻找我的问题的解决方案,因为 html2text 是一个很好的库,它允许我配置一些选项,比如我用超链接显示的那些,如果有一个基于这个库的解决方案会很好.
更新:
我有一个使用 BeautifulSoup 库的解决方案,但我认为它是一个临时补丁,因为它添加了另一个依赖项并且添加了许多不必要的处理。我在这里所做的是编辑 HTML before 解析成 markdown :
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。
【问题讨论】:
标签: python html parsing markdown