介绍C#解析HTML的两种方法

开发 后端
在搜索引擎的开发中,我们需要对Html进行解析。本文介绍C#解析HTML的两种方法。

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

C#解析Html的第一种方法:

用System.Net.WebClient下载Web Page存到本地文件或者String中,用正则表达式来分析。这个方法可以用在Web Crawler等需要分析很多Web Page的应用中。

估计这也是大家最直接,最容易想到的一个方法。

转自网上的一个实例:所有的href都抽取出来:

  1. using System;  
  2. using System.Net;  
  3. using System.Text;  
  4. using System.Text.RegularExpressions;  
  5. namespace HttpGet  
  6. {  
  7.     class Class1  
  8.     {  
  9.         [STAThread]  
  10.         static void Main(string[] args)  
  11.         {  
  12.             System.Net.WebClient client = new WebClient();  
  13.             byte[] page = client.DownloadData("http://www.google.com");  
  14.             string content = System.Text.Encoding.UTF8.GetString(page);  
  15.             string regex = "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']";  
  16.             Regex re = new Regex(regex);  
  17.             MatchCollection matches = re.Matches(content);  
  18.  
  19.             System.Collections.IEnumerator enu = matches.GetEnumerator();  
  20.             while (enu.MoveNext() && enu.Current != null)  
  21.             {  
  22.                 Match match = (Match)(enu.Current);  
  23.                 Console.Write(match.Value + "\r\n");  
  24.             }  
  25.         }  
  26.     }  

一些爬虫的HTML解析中也是用的类似的方法。

C#解析Html的第二种方法:

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

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

自己做了个实例:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using Winista.Text.HtmlParser;  
  10. using Winista.Text.HtmlParser.Lex;  
  11. using Winista.Text.HtmlParser.Util;  
  12. using Winista.Text.HtmlParser.Tags;  
  13. using Winista.Text.HtmlParser.Filters;  
  14.  
  15.  
  16. namespace HTMLParser  
  17. {  
  18.     public partial class Form1 : Form  
  19.     {  
  20.         public Form1()  
  21.         {  
  22.             InitializeComponent();  
  23.             AddUrl();  
  24.         }  
  25.  
  26.         private void btnParser_Click(object sender, EventArgs e)  
  27.         {  
  28.             #region 获得网页的html  
  29.             try 
  30.             {  
  31.  
  32.                 txtHtmlWhole.Text = "";  
  33.                 string url = CBUrl.SelectedItem.ToString().Trim();  
  34.                 System.Net.WebClient aWebClient = new System.Net.WebClient();  
  35.                 aWebClient.Encoding = System.Text.Encoding.Default;  
  36.                 string html = aWebClient.DownloadString(url);  
  37.                 txtHtmlWhole.Text = html;  
  38.             }  
  39.             catch (Exception ex)  
  40.             {  
  41.                 MessageBox.Show(ex.Message);  
  42.             }  
  43.             #endregion  
  44.  
  45.             #region 分析网页html节点  
  46.             Lexer lexer = new Lexer(this.txtHtmlWhole.Text);  
  47.             Parser parser = new Parser(lexer);  
  48.             NodeList htmlNodes = parser.Parse(null);  
  49.             this.treeView1.Nodes.Clear();  
  50.             this.treeView1.Nodes.Add("root");  
  51.             TreeNode treeRoot = this.treeView1.Nodes[0];  
  52.             for (int i = 0; i <  htmlNodes.Count; i++)  
  53.             {  
  54.                 this.RecursionHtmlNode(treeRoot, htmlNodes[i], false);  
  55.             }  
  56.  
  57.             #endregion  
  58.  
  59.         }  
  60.  
  61.         private void RecursionHtmlNode(TreeNode treeNode, INode htmlNode, bool siblingRequired)  
  62.         {  
  63.             if (htmlNode == null || treeNode == nullreturn;  
  64.  
  65.             TreeNode current = treeNode;  
  66.             TreeNode content ;  
  67.             //current node  
  68.             if (htmlNode is ITag)  
  69.             {  
  70.                 ITag tag = (htmlNode as ITag);  
  71.                 if (!tag.IsEndTag())  
  72.                 {  
  73.                     string nodeString = tag.TagName;  
  74.                     if (tag.Attributes != null && tag.Attributes.Count > 0)  
  75.                     {  
  76.                         if (tag.Attributes["ID"] != null)  
  77.                         {  
  78.                             nodeString = nodeString + " { id=\"" + tag.Attributes["ID"].ToString() + "\" }";  
  79.                         }  
  80.                         if (tag.Attributes["HREF"] != null)  
  81.                         {  
  82.                             nodeString = nodeString + " { href=\"" + tag.Attributes["HREF"].ToString() + "\" }";  
  83.                         }  
  84.                     }  
  85.                       
  86.                     current = new TreeNode(nodeString);  
  87.                     treeNode.Nodes.Add(current);  
  88.                 }  
  89.             }  
  90.  
  91.             //获取节点间的内容  
  92.             if (htmlNode.Children != null && htmlNode.Children.Count > 0)  
  93.             {  
  94.                 this.RecursionHtmlNode(current, htmlNode.FirstChild, true);  
  95.                 content = new TreeNode(htmlNode.FirstChild.GetText());  
  96.                 treeNode.Nodes.Add(content);  
  97.             }  
  98.  
  99.             //the sibling nodes  
  100.             if (siblingRequired)  
  101.             {  
  102.                 INode sibling = htmlNode.NextSibling;  
  103.                 while (sibling != null)  
  104.                 {  
  105.                     this.RecursionHtmlNode(treeNode, sibling, false);  
  106.                     sibling = sibling.NextSibling;  
  107.                 }  
  108.             }  
  109.         }  
  110.         private void AddUrl()  
  111.         {  
  112.             CBUrl.Items.Add("http://www.hao123.com");  
  113.             CBUrl.Items.Add("http://www.sina.com");  
  114.             CBUrl.Items.Add("http://www.heuet.edu.cn");  
  115.         }  
  116.  
  117.           
  118.  
  119.     }  

运行效果:

运行效果 

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

小结:

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

【编辑推荐】

  1. 解密C#-SQLite是如何移植的
  2. 看看如何透过JavaScript调用C#函数
  3. 浅析C#事件注册和注销
  4. 示例:C#通过AMO对象浏览SQL SERVER 2005 SSAS
  5. C#隐藏窗口的几种方法
责任编辑:book05 来源: cnblogs
相关推荐

2009-08-05 13:34:18

C#日期相减

2009-08-17 08:29:00

c#删除指定文件

2009-08-21 18:02:41

C#快捷键

2009-08-25 11:35:27

C#连接数据库

2010-06-17 12:48:05

livecd 修复Gr

2009-08-17 17:48:00

C#自定义鼠标样式

2009-08-03 17:53:11

XML数据

2009-06-17 17:37:43

Java随机数

2009-12-07 13:42:24

WCF框架

2010-08-04 17:41:52

挂载NFS

2011-04-25 09:53:31

C++mysql

2010-11-24 14:36:25

修复mysql表

2011-03-30 17:04:24

MySQL添加用户

2009-09-25 14:04:09

Hibernate eHibernate h

2010-04-13 09:50:44

Oracle跟踪

2011-05-24 09:18:59

C++连接mysql数据库

2010-11-10 13:22:41

SQL Server备

2010-09-13 13:05:03

sql server分

2010-11-09 13:09:58

SQL Server分

2009-07-31 14:04:11

C#时间比较大小
点赞
收藏

51CTO技术栈公众号