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

如何用JavaScript、jQuery或C#提取HTML标签并统计频次

刚好做过类似的需求,给你分享两个实用的实现方案,分别用JavaScript和C#来完成你要的功能——从HTML字符串里提取所有带属性的标签、生成完整列表,还能统计标签出现频次并找出Top3。

JavaScript 实现方案

如果是前端场景,用正则就能快速实现,不过要注意正则处理HTML的边缘情况(比如属性值里包含特殊字符),这里给的正则已经覆盖了大部分常见场景:

// 你的示例HTML字符串
const htmlStr = '<html> <head> </head> <body> qwe <button type="button">Click Me!</button> <a>xyz</a> <button type="button"/> </body> </html>';

// 匹配所有HTML标签的正则(支持开始标签、结束标签、自闭合标签,保留属性)
const tagRegex = /<\/?[\w-]+(?:\s+[\w-]+(?:="[^"]*")?)*\s*\/?>/g;

// 提取所有标签到列表
const allTags = htmlStr.match(tagRegex) || [];

// 👉 两种统计方式可选:

// 1. 按完整标签字符串统计(比如<button type="button">和<button>视为不同标签)
const fullTagCount = {};
allTags.forEach(tag => {
  fullTagCount[tag] = (fullTagCount[tag] || 0) + 1;
});

// 2. 按标签名统计(不管属性、开始/结束/自闭合,统一按标签名计数)
const getTagName = tag => {
  const match = tag.match(/<\/?([\w-]+)/);
  return match ? match[1] : null;
};
const tagNameCount = {};
allTags.forEach(tag => {
  const name = getTagName(tag);
  if (name) tagNameCount[name] = (tagNameCount[name] || 0) + 1;
});

// 获取频次最高的3个标签(这里用按标签名统计的结果)
const top3Tags = Object.entries(tagNameCount)
  .sort((a, b) => b[1] - a[1])
  .slice(0, 3);

// 输出结果
console.log('提取到的标签列表:', allTags);
console.log('按标签名统计的频次:', tagNameCount);
console.log('Top3高频标签:', top3Tags);

结果说明

对示例字符串处理后:

  • 提取到的标签列表:["<html>", "<head>", "</head>", "<body>", "<button type=\"button\">", "</button>", "<a>", "</a>", "<button type=\"button\"/>", "</body>", "</html>"]
  • 按标签名统计的频次:{html:2, head:2, body:2, button:3, a:2}
  • Top3高频标签:[["button",3], ["html",2], ["head",2]](后面的并列标签会按顺序取前3)

C# 实现方案

后端场景更推荐用专业的HTML解析库HtmlAgilityPack,比正则更可靠,能处理复杂HTML结构(比如嵌套标签、属性含特殊字符等)。

步骤1:安装依赖

先通过NuGet安装HtmlAgilityPack包:

Install-Package HtmlAgilityPack

步骤2:实现代码

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace HtmlTagExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            // 示例HTML字符串
            string htmlStr = "<html> <head> </head> <body> qwe <button type=\"button\">Click Me!</button> <a>xyz</a> <button type=\"button\"/> </body> </html>";

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlStr);

            // 提取所有完整标签(含属性)
            List<string> allTags = new List<string>();
            foreach (HtmlNode node in doc.DocumentNode.DescendantsAndSelf())
            {
                // 添加开始标签或自闭合标签的完整字符串
                if (!node.IsClosingNode)
                {
                    var tagEndIndex = node.OuterHtml.IndexOf('>') + 1;
                    allTags.Add(node.OuterHtml.Substring(0, tagEndIndex));
                }
                // 添加结束标签
                else if (node.NodeType == HtmlNodeType.Element)
                {
                    allTags.Add($"</{node.Name}>");
                }
            }

            // 按标签名统计频次
            var tagNameCount = allTags
                .Select(tag => Regex.Match(tag, @"<\/?([\w-]+)").Groups[1].Value)
                .GroupBy(name => name)
                .ToDictionary(g => g.Key, g => g.Count());

            // 获取Top3高频标签
            var top3Tags = tagNameCount
                .OrderByDescending(kv => kv.Value)
                .Take(3)
                .ToList();

            // 输出结果
            Console.WriteLine("提取到的所有标签:");
            allTags.ForEach(tag => Console.WriteLine(tag));

            Console.WriteLine("\n标签频次统计:");
            foreach (var kv in tagNameCount)
            {
                Console.WriteLine($"{kv.Key}: {kv.Value}次");
            }

            Console.WriteLine("\n频次最高的3个标签:");
            top3Tags.ForEach(kv => Console.WriteLine($"{kv.Key}: {kv.Value}次"));
        }
    }
}

结果说明

运行后得到的结果和JavaScript方案一致,而且HtmlAgilityPack能处理更复杂的HTML(比如属性里包含>、标签嵌套异常等),稳定性更强。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:30:37