python去除html标签的方法:1、“pattern.sub('',html)”方法;2、“BeautifulSoup(html,'html.parser')”方法;3、“response.xpath('string(.)')”方法。

本文操作环境:windows7系统、python3.6.4版,DELL G3电脑。
python去除html标签的几种方法
import re
from bs4 import BeautifulSoup
from lxml import etree
html = '<p>你好</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill9965" title="macOS UI 自动化技能包 —— 用 Python 控制你的 Mac"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dbae7c507.jpg" alt="macOS UI 自动化技能包 —— 用 Python 控制你的 Mac" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill9965" title="macOS UI 自动化技能包 —— 用 Python 控制你的 Mac" class="overflowclass">macOS UI 自动化技能包 —— 用 Python 控制你的 Mac</a>
<p class="overflowclass">让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript
系统要求
macOS 14+ (Sonoma)
Python 3.9+
需要开启:辅助功能 + 屏幕录制权限</p>
</div>
<a rel="nofollow" href="/xiazai/skill9965" title="macOS UI 自动化技能包 —— 用 Python 控制你的 Mac" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><br><font>哈哈</font><b>大家好</b>'
# 方法一
pattern = re.compile(r']+>',re.S)
result = pattern.sub('', html)
print(result)
<br># 方法二
soup = BeautifulSoup(html,'html.parser')
print(soup.get_text())
# 方法三
response = etree.HTML(text=html)
# print(dir(response))
print(response.xpath('string(.)'))
# 你好哈哈大家好
# 你好哈哈大家好
# 你好哈哈大家好
【推荐:python视频教程】
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










