天天看點

【轉】C#解析HTML

在搜尋引擎的開發中,我們需要對網頁的Html内容進行檢索,難免的就需要對Html進行解析。拆分每一個節點并且擷取節點間的内容。此文介紹兩種C#解析Html的方法。

第一種方法:

用System.Net.WebClient下載下傳Web Page存到本地檔案或者String中,用正規表達式來分析。這個方法可以用在Web Crawler等需要分析很多Web Page的應用中。

估計這也是大家最直接,最容易想到的一個方法。

轉自網上的一個執行個體:所有的href都抽取出來:

【轉】C#解析HTML
【轉】C#解析HTML

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

一些爬蟲的HTML解析中也是用的類似的方法。

第二種方法:

利用Winista.Htmlparser.Net 解析Html。這是.NET平台下解析Html的開源代碼,網上有源碼下載下傳,百度一下就能搜到,這裡就不提供了。并且有英文的幫助文檔。找不到的留下郵箱。

個人認為這是.net平台下解析html不錯的解決方案,基本上能夠滿足我們對html的解析工作。

自己做了個執行個體:

【轉】C#解析HTML
【轉】C#解析HTML

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

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);

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

運作效果:

【轉】C#解析HTML

實作取來很容易,結合Winista.Htmlparser源碼很快就可以實作想要的效果。

小結:

簡單介紹了兩種解析Html的方法,大家有什麼其他好的方法還望指教。

本文轉自齊師傅部落格園部落格,原文連結:http://www.cnblogs.com/youring2/archive/2012/04/11/2442828.html,如需轉載請自行聯系原作者