You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从HTML字符串中分别提取正文描述与ul/li列表项文本

问题原因

你之前的正则方案失效是两个核心问题导致的:

  • 原始字符串经过双重HTML实体转义:外层div标签被转义为&lt;div&gt;格式,内层p/ul/li标签更是被转义为&amp;lt;p&amp;gt;格式,你写的正则匹配<div>这类未转义的标签格式,根本无法命中目标内容。
  • 正则逻辑没有区分正文区和列表区,粗暴删除标签再分割的逻辑,很容易残留转义字符、多余标签片段,也无法精准批量提取li内的内容。
推荐实现方案

优先用原生DOM解析方式实现,比正则容错率高,不会因为标签新增自定义属性、格式微调就失效:

const rawHtml = productDetails.description;
const parser = new DOMParser();

// 两次解码,还原真实DOM结构
const outerLayer = parser.parseFromString(rawHtml, 'text/html');
const innerEscaped = outerLayer.body.firstChild.textContent;
const realDom = parser.parseFromString(innerEscaped, 'text/html');

// 提取正文
const productDesc = realDom.querySelector('p').textContent.trim();

// 提取特性列表
const featureItems = Array.from(realDom.querySelectorAll('ul li'))
  .map(item => item.textContent.trim());
提取结果

执行后得到的内容完全符合预期:

  • 描述正文:The Angelina Tank Dress is simple yet sophisticated. This dress can be thrown over a swimsuit for last minute lunch plans or belted for dinner on the patio. The high-low hemline gives it the perfect amount of swing.
  • 特性列表:
    • Scoopneck
    • Sleeveless
    • Hits below the knee
    • Longer back hemline
    • Machine wash, tumble dry low

如果你是在Node.js环境运行,没有浏览器原生DOMParser对象,可以引入jsdom这类DOM解析库实现相同逻辑,不推荐用复杂正则硬匹配HTML结构,后续维护成本极高。

内容的提问来源于stack exchange,提问作者LosMos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 13:27:17