python - 如何在 Python 中将 HTML 转换为没有标记的文本?

标签 python html

我需要在遵守 <br> 的同时从 HTML 文档中获取纯文本元素作为换行符。 BeautifulSoup.text不处理 <br>和换行符。 HTML2Text 非常好,但它会转换为 markdown。我还能如何解决这个问题?

最佳答案

我喜欢用下面的方法。你可以做一个手册.replace('<br>','\r\n')在将其传递给 strip_tags(html) 之前在字符串上兑现新线路。

来自 this question :

from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

关于python - 如何在 Python 中将 HTML 转换为没有标记的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17011732/

相关文章:

python - 从给定列表创建一个新列表,以便新列表可以标记给定列表中的连续重复

python - Flask 属性错误与 unpickling

jQuery 可排序/可拖动列表 disableselection() 不工作

html - 我无法理解 CSS : first-child

python - 将数据框保存到 Excel 后,我无法打开 Excel 文件

python - 如何在 Python 2.7.2 中计算一组 GPS 卫星的 DOP 值?

python - aiohttp ClientSession.get() 方法静默失败 - Python3.7

javascript秒表用户输入

标签内的 HTML 标签未显示

javascript - jQuery find() 只返回第一个匹配的结果?