字符串列表或数组包含Html源代码中的特定单词

本文关键字:单词 源代码 Html 列表 数组 包含 字符串 | 更新日期: 2023-09-27 18:26:29

我想开发一个程序,可以计算源代码中的html标签,所以我写了一个代码来获取这样的网站源代码。

WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
    source = reader.ReadToEnd();
}

通过这种方式,我可以获取站点的源代码并绑定到字符串。接下来我想要的是控制字符串和计数html /html body /body p /p bla bla。什么是LINQ方式来计算源代码中的所有html标签并显示类似的结果

HTML:2

身体:2

UL:42

字符串列表或数组包含Html源代码中的特定单词

您可以使用HtmlAgilityPack解析HTML并递归计数所有标签:

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(source);
int allTags = doc.DocumentNode.Descendants().Count();

如果只想计数特定标签(例如UL),请将Descendants更改为Descendants("UL")

请注意,这被算作一个UL标签(而不是两个):

   <ul>
      <li><a id=""menuSubItem1""></a></li>
      <li><a id=""menuSubItem2""></a></li>
   </ul>

您也可以使用HtmlAgilityPack直接从web解析html:

var web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load("http://google.com");
int countAll = doc.DocumentNode.Descendants().Count();
int countHtml = doc.DocumentNode.Descendants("HTML").Count();
int countBody = doc.DocumentNode.Descendants("BODY").Count();
int countUL = doc.DocumentNode.Descendants("UL").Count();

我推荐HtmlAgilityPack

var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(source);
var nodes = htmlDocument.DocumentNode
            .Descendants()
            .GroupBy(x => x.Name)
            .ToDictionary(x => x.Key, x => x.Count() * 2);

通过这种方式,您可以很容易地按名称对所有标签进行分组,并使用nodes["html"]获取特定节点的计数。

Descendants也会返回文本节点,标签之间的文本算作一个节点。它还将包括评论。如果您只想获得元素节点,您可以添加:

.Where(x => x.NodeType == HtmlNodeType.Element)

GroupBy