我想要开发一个程序,可以计数在源代码中的html标记,所以我写了一个代码,以获取网站的源代码如下。
WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}通过这种方式,我可以获取站点的源代码并绑定到string。接下来,我想要的是控制字符串和计数html /html body /body p /p bla bla bla。什么是LINQ方法来计数源代码中的所有html标记并显示结果
HTML: 2 机构:2 UL:42
发布于 2014-10-14 08:07:55
您可以使用HtmlAgilityPack来解析HTML并递归计数所有标记:
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(source);
int allTags = doc.DocumentNode.Descendants().Count();如果您只想计数特定的标签(F.E。( 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();https://stackoverflow.com/questions/26355616
复制相似问题