Python 将 html 转换为文本并模仿格式

2023-11-27

我正在学习 BeautifulSoup,并发现了许多“html2text”解决方案,但我正在寻找的解决方案应该模仿格式:

<ul>
<li>One</li>
<li>Two</li>
</ul>

会成为

* One
* Two

and

Some text
<blockquote>
More magnificent text here
</blockquote>
Final text

to

Some text

    More magnificent text here

Final text

我正在阅读文档,但我没有看到任何直接的内容。有什么帮助吗?我愿意使用除了 beautifulsoup 之外的其他东西。


看看亚伦·斯沃茨的html2text脚本(可以安装pip install html2text)。注意输出有效Markdown。如果由于某种原因不完全适合您,一些相当琐碎的调整应该可以让您得到问题中的确切输出:

In [1]: import html2text

In [2]: h1 = """<ul>
   ...: <li>One</li>
   ...: <li>Two</li>
   ...: </ul>"""

In [3]: print html2text.html2text(h1)
  * One
  * Two

In [4]: h2 = """<p>Some text
   ...: <blockquote>
   ...: More magnificent text here
   ...: </blockquote>
   ...: Final text</p>"""

In [5]: print html2text.html2text(h2)
Some text

> More magnificent text here

Final text
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 将 html 转换为文本并模仿格式 的相关文章