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

如何用Cheerio解析含<b>、<br>标签的HTML为指定字符串数组?

问题描述

需要解析Moonbreaker Wiki页面中如下结构的div元素:

<div class="pi-smart-data-value pi-data-value pi-font pi-item-spacing pi-border-color" style="width: calc(1 / 1 * 100%)" data-source="unique_ability"><b>Captain</b><br /><b>"Back off!"</b><br />Push target on hit.</div>

目标是将内容解析为数组:["Captain", "Back off!", "Push target on hit."]

使用Cheerio的text()方法会得到拼接后的长字符串:Captain"Back off!"Push target on hit.;使用html()方法得到的HTML内容又难以直接解析成目标格式,该如何实现?

解决方案

可以通过以下几种实用方式实现:

方法一:遍历div子节点提取有效文本

利用Cheerio遍历目标div的所有子节点,过滤掉<br>标签,提取并清理每个节点的文本内容:

const $ = cheerio.load(htmlContent);
const targetDiv = $('.pi-smart-data-value[data-source="unique_ability"]');
const result = [];

targetDiv.contents().each((_, node) => {
  // 过滤br标签和空文本节点
  if (node.type !== 'tag' || node.name !== 'br') {
    const text = $(node).text().trim();
    if (text) {
      // 去除文本首尾的多余引号
      const cleanedText = text.replace(/^"|"$/g, '');
      result.push(cleanedText);
    }
  }
});

console.log(result); // 输出 ["Captain", "Back off!", "Push target on hit."]

方法二:按<br>分割HTML后处理

先获取div的HTML内容,按<br>分割为片段,再逐个提取文本并清理:

const $ = cheerio.load(htmlContent);
const targetDiv = $('.pi-smart-data-value[data-source="unique_ability"]');
const html = targetDiv.html();
const parts = html.split('<br />');

const result = parts.map(part => {
  // 解析片段文本,去除标签和首尾引号
  const text = $(part).text().trim().replace(/^"|"$/g, '');
  return text;
}).filter(text => text); // 过滤空字符串

console.log(result); // 输出目标数组

方法三:结合children()和contents()提取

先提取所有<b>标签的文本,再处理最后一段无标签的文本内容:

const $ = cheerio.load(htmlContent);
const targetDiv = $('.pi-smart-data-value[data-source="unique_ability"]');
const result = [];

// 提取所有b标签的文本
targetDiv.find('b').each((_, el) => {
  const text = $(el).text().trim().replace(/^"|"$/g, '');
  result.push(text);
});

// 提取最后一个br之后的文本
const lastText = targetDiv.contents().last().text().trim();
if (lastText) {
  result.push(lastText);
}

console.log(result); // 输出目标数组

内容的提问来源于stack exchange,提问作者Miha Šušteršič

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:55:21