首頁 後端開發 C#.Net教程 C#下解析HTML的兩種方法介紹

C#下解析HTML的兩種方法介紹

Jan 13, 2017 pm 05:21 PM

在搜索引擎的开发中,我们需要对Html进行解析。本文介绍C#解析HTML的两种方法。
AD: 
在搜索引擎的开发中,我们需要对网页的Html内容进行检索,难免的就需要对Html进行解析。拆分每一个节点并且获取节点间的内容。此文介绍两种C#解析Html的方法。

C#解析Html的第一种方法:
用System.Net.WebClient下载Web Page存到本地文件或者String中,用正则表达式来分析。这个方法可以用在Web Crawler等需要分析很多Web Page的应用中。
估计这也是大家最直接,最容易想到的一个方法。
转自网上的一个实例:所有的href都抽取出来:

using System; 
using System.Net; 
using System.Text; 
using System.Text.RegularExpressions; 
namespace HttpGet 
{ 
class Class1 
{ 
[STAThread] 
static void Main(string[] args) 
{ 
System.Net.WebClient client = new WebClient(); 
byte[] page = client.DownloadData("http://www.google.com"); 
string content = System.Text.Encoding.UTF8.GetString(page); 
string regex = "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']"; 
Regex re = new Regex(regex); 
MatchCollection matches = re.Matches(content);
System.Collections.IEnumerator enu = matches.GetEnumerator(); 
while (enu.MoveNext() && enu.Current != null) 
{ 
Match match = (Match)(enu.Current); 
Console.Write(match.Value + "\r\n"); 
} 
} 
} 
}
登入後複製

C#解析Html的第二种方法:
利用Winista.Htmlparser.Net 解析Html。这是.NET平台下解析Html的开源代码,网上有源码下载,百度一下就能搜到,这里就不提供了。并且有英文的帮助文档。找不到的留下邮箱。

个人认为这是.net平台下解析html不错的解决方案,基本上能够满足我们对html的解析工作。
自己做了个实例:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using Winista.Text.HtmlParser; 
using Winista.Text.HtmlParser.Lex; 
using Winista.Text.HtmlParser.Util; 
using Winista.Text.HtmlParser.Tags; 
using Winista.Text.HtmlParser.Filters;

namespace HTMLParser 
{ 
public partial class Form1 : Form 
{ 
public Form1() 
{ 
InitializeComponent(); 
AddUrl(); 
}
private void btnParser_Click(object sender, EventArgs e) 
{ 
#region 获得网页的html 
try 
{
txtHtmlWhole.Text = ""; 
string url = CBUrl.SelectedItem.ToString().Trim(); 
System.Net.WebClient aWebClient = new System.Net.WebClient(); 
aWebClient.Encoding = System.Text.Encoding.Default; 
string html = aWebClient.DownloadString(url); 
txtHtmlWhole.Text = html; 
} 
catch (Exception ex) 
{ 
MessageBox.Show(ex.Message); 
} 
#endregion
#region 分析网页html节点 
Lexer lexer = new Lexer(this.txtHtmlWhole.Text); 
Parser parser = new Parser(lexer); 
NodeList htmlNodes = parser.Parse(null); 
this.treeView1.Nodes.Clear(); 
this.treeView1.Nodes.Add("root"); 
TreeNode treeRoot = this.treeView1.Nodes[0]; 
for (int i = 0; i < htmlNodes.Count; i++) 
{ 
this.RecursionHtmlNode(treeRoot, htmlNodes[i], false); 
}
#endregion
}
private void RecursionHtmlNode(TreeNode treeNode, INode htmlNode, bool siblingRequired) 
{ 
if (htmlNode == null || treeNode == null) return;
TreeNode current = treeNode; 
TreeNode content ; 
//current node 
if (htmlNode is ITag) 
{ 
ITag tag = (htmlNode as ITag); 
if (!tag.IsEndTag()) 
{ 
string nodeString = tag.TagName; 
if (tag.Attributes != null && tag.Attributes.Count > 0) 
{ 
if (tag.Attributes["ID"] != null) 
{ 
nodeString = nodeString + " { id=\"" + tag.Attributes["ID"].ToString() + "\" }"; 
} 
if (tag.Attributes["HREF"] != null) 
{ 
nodeString = nodeString + " { href=\"" + tag.Attributes["HREF"].ToString() + "\" }"; 
} 
}
current = new TreeNode(nodeString); 
treeNode.Nodes.Add(current); 
} 
} 
//获取节点间的内容 
if (htmlNode.Children != null && htmlNode.Children.Count > 0) 
{ 
this.RecursionHtmlNode(current, htmlNode.FirstChild, true); 
content = new TreeNode(htmlNode.FirstChild.GetText()); 
treeNode.Nodes.Add(content); 
} 
//the sibling nodes 
if (siblingRequired) 
{ 
INode sibling = htmlNode.NextSibling; 
while (sibling != null) 
{ 
this.RecursionHtmlNode(treeNode, sibling, false); 
sibling = sibling.NextSibling; 
} 
} 
} 
private void AddUrl() 
{ 
CBUrl.Items.Add("http://www.hao123.com"); 
CBUrl.Items.Add("http://www.sina.com"); 
CBUrl.Items.Add("http://www.heuet.edu.cn"); 
} 
} 
}
登入後複製

运行效果:

C#下解析HTML的兩種方法介紹

实现取来很容易,结合Winista.Htmlparser源码很快就可以实现想要的效果。

小结:
简单介绍了两种C#解析Html的的方法,大家有什么其他好的方法还望指教。

更多C#下解析HTML的兩種方法介紹相关文章请关注PHP中文网!


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1319
25
PHP教程
1269
29
C# 教程
1248
24
c#.net的持續相關性:查看當前用法 c#.net的持續相關性:查看當前用法 Apr 16, 2025 am 12:07 AM

C#.NET依然重要,因為它提供了強大的工具和庫,支持多種應用開發。 1)C#結合.NET框架,使開發高效便捷。 2)C#的類型安全和垃圾回收機制增強了其優勢。 3).NET提供跨平台運行環境和豐富的API,提升了開發靈活性。

從網絡到桌面:C#.NET的多功能性 從網絡到桌面:C#.NET的多功能性 Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#作為多功能.NET語言:應用程序和示例 C#作為多功能.NET語言:應用程序和示例 Apr 26, 2025 am 12:26 AM

C#在企業級應用、遊戲開發、移動應用和Web開發中均有廣泛應用。 1)在企業級應用中,C#常用於ASP.NETCore開發WebAPI。 2)在遊戲開發中,C#與Unity引擎結合,實現角色控制等功能。 3)C#支持多態性和異步編程,提高代碼靈活性和應用性能。

c#.net適合您嗎?評估其適用性 c#.net適合您嗎?評估其適用性 Apr 13, 2025 am 12:03 AM

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#.NET與未來:適應新技術 C#.NET與未來:適應新技術 Apr 14, 2025 am 12:06 AM

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

.NET中的C#代碼:探索編程過程 .NET中的C#代碼:探索編程過程 Apr 12, 2025 am 12:02 AM

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

將C#.NET應用程序部署到Azure/AWS:逐步指南 將C#.NET應用程序部署到Azure/AWS:逐步指南 Apr 23, 2025 am 12:06 AM

如何將C#.NET應用部署到Azure或AWS?答案是使用AzureAppService和AWSElasticBeanstalk。 1.在Azure上,使用AzureAppService和AzurePipelines自動化部署。 2.在AWS上,使用AmazonElasticBeanstalk和AWSLambda實現部署和無服務器計算。

C#和.NET運行時:它們如何一起工作 C#和.NET運行時:它們如何一起工作 Apr 19, 2025 am 12:04 AM

C#和.NET運行時緊密合作,賦予開發者高效、強大且跨平台的開發能力。 1)C#是一種類型安全且面向對象的編程語言,旨在與.NET框架無縫集成。 2).NET運行時管理C#代碼的執行,提供垃圾回收、類型安全等服務,確保高效和跨平台運行。

See all articles