方法1:使用 BeautifulSoup(推荐)

from bs4 import BeautifulSoup

html = "<p>Hello <b>World</b>! <a href='#'>Click</a></p>"
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()
print(text)  # Hello World! Click

方法2:使用正则表达式(简单场景)

import re

html = "<p>Hello <b>World</b>! <a href='#'>Click</a></p>"
text = re.sub(r'<[^>]+>', '', html)
print(text)  # Hello World! Click

方法3:使用 html.parser(标准库)

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.text = []
    
    def handle_data(self, data):
        self.text.append(data)
    
    def get_text(self):
        return ''.join(self.text)

html = "<p>Hello <b>World</b>!</p>"
parser = MyHTMLParser()
parser.feed(html)
print(parser.get_text())  # Hello World!

方法4:使用 lxml(性能最好)

from lxml import html

html_str = "<p>Hello <b>World</b>!</p>"
tree = html.fromstring(html_str)
text = tree.text_content()
print(text)  # Hello World!

📊 对比

方法 优点 缺点
BeautifulSoup 简单易用,容错强 需要安装第三方库
正则 无需安装,速度快 复杂HTML可能出错
html.parser 标准库,无需安装 代码稍多
lxml 速度最快,功能强大 需要安装C库

推荐:一般用 BeautifulSoup,简单场景用正则

pip install beautifulsoup4 lxml

更多推荐