textcontent提取html纯文本最快最安全,浏览器中临时创建div并赋innerhtml后读取textcontent即可;服务端推荐beautifulsoup.get_text(),正则删标签易漏注释、脚本、实体且不处理嵌套。

直接用 textContent 最快最安全,但得在浏览器环境里;服务端用 BeautifulSoup.get_text() 更稳,别信正则删标签——它会漏掉注释、脚本、自闭合标签里的文本,还容易把实体字符(如 )搞成乱码。
浏览器里一行搞定:用 textContent 而不是 innerText
临时创建一个 div,把 HTML 字符串塞进 innerHTML,再读它的 textContent:
const htmlString = '<p>Hello</p><script>alert(1)</script> World';
const temp = document.createElement('div');
temp.innerHTML = htmlString;
const text = temp.textContent; // → "Hello World"
注意:textContent 不执行脚本、不渲染样式、不处理 CSS display: none,但能正确解码实体( → 全角空格);innerText 会受样式影响,且 IE 兼容性差,不推荐用于提取。
- 如果原始 HTML 含有
<!-- comment -->,textContent会忽略它——这是对的 - 如果需要把多个空白符压缩成单个空格,额外加
.replace(/\s+/g, ' ').trim() - 不要对用户输入的 HTML 直接赋给
innerHTML后再执行脚本——有 XSS 风险;纯提取文本则无害
Python 服务端首选:用 BeautifulSoup 的 get_text()
比 html.unescape() + re.sub() 可靠得多,能处理嵌套、换行、换段逻辑:
from bs4 import BeautifulSoup html = '<div> <p>Line1</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill9263" title="Html2md"><img src="https://img.php.cn/upload/skill/000/000/081/179249945220127.jpg" alt="Html2md" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill9263" title="Html2md" class="overflowclass">Html2md</a> <p class="overflowclass">使用 Readability + Turndown 将 HTML 页面转换为干净的、Agent 友好的 Markdown。去除导航栏、广告、页脚、Cookie 横幅、社交按钮等干扰元素。支持 URL...</p> </div> <a rel="nofollow" href="/xiazai/skill9263" title="Html2md" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> <p>Line2</p> </div>' soup = BeautifulSoup(html, 'html.parser') text = soup.get_text(separator='\n', strip=True) # → "Line1\nLine2"
- 必须指定解析器,
'html.parser'足够轻量;若 HTML 极度不规范,可换'lxml' -
separator控制块级元素间分隔符,默认是空字符串,容易粘连;设为'\n'更符合阅读习惯 -
strip=True自动清理首尾空白,但不会触碰中间缩进——这点比手写正则可控得多 - 避免用
soup.text:它不支持separator和strip参数,行为不可控
避开正则陷阱:为什么 re.sub(r"]*>", "", s) 不可靠
它看似简单,实际会在这些地方翻车:
- 匹配
<script>console.log("<div>")</script>时,第一个和最近的 <code>>配对,导致中间引号内 HTML 被误删 - 跳过注释
<!-- <p>ignored</p> -->,但正则没排除注释区域,可能把-->当标签尾截断 - 无法识别
、<等实体,输出里全是字面符号而非对应字符 - 自闭合标签如
<br>或<img src="x">在某些正则下可能漏匹配
除非你 100% 确认输入是极简、无脚本、无注释、无实体的 HTML 片段,否则别用正则做提取主逻辑。
提取“父元素内直接文本”,避开子标签内容
比如这个结构:<p><strong>Title:</strong> Actual content here.</p>,只想拿 "Actual content here.",不要 "Title:":
- 在浏览器中:用
Array.from(p.childNodes).filter(n => n.nodeType === 3).map(n => n.textContent).join('').trim()——只取文本节点(nodeType 3) - 在 BeautifulSoup 中:
p.get_text(strip=True)会返回全部;要精确控制,得遍历p.children,跳过Tag类型,只拼接bs4.element.NavigableString - 用 lxml + XPath:
//p/text()只取直接子文本节点,不进<strong></strong>;但注意它会返回多个字符串,需''.join()
这类需求本质是 DOM 树遍历问题,不是“去标签”,而是“选节点”。用错方法(比如先删标签再切分)极易把空格、换行逻辑搞崩。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










