C#解析HTML

第一种方法:用正则表达式来分析

[csharp]  view plain copy
  1. 转自网上的一个实例:所有的href都抽取出来:  
  2. using System;  
  3. using System.Net;  
  4. using System.Text;  
  5. using System.Text.RegularExpressions;  
  6. namespace HttpGet  
  7. {  
  8.     class Class1  
  9.     {  
  10.         [STAThread]  
  11.         static void Main(string[] args)  
  12.         {  
  13.             System.Net.WebClient client = new WebClient();  
  14.             byte[] page = client.DownloadData("http://www.google.com");  
  15.             string content = System.Text.Encoding.UTF8.GetString(page);  
  16.             string regex = "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']";  
  17.             Regex re = new Regex(regex);  
  18.             MatchCollection matches = re.Matches(content);  
  19.   
  20.             System.Collections.IEnumerator enu = matches.GetEnumerator();  
  21.             while (enu.MoveNext() && enu.Current != null)  
  22.             {  
  23.                 Match match = (Match)(enu.Current);  
  24.                 Console.Write(match.Value + "\r\n");  
  25.             }  
  26.         }  
  27.     }  
  28. }  
  29.   
  30. 一些爬虫的HTML解析中也是用的类似的方法。  


第二中方法: 利用Winista.Htmlparser.Net 解析Html

1.  下载:

http://www.netomatix.com/Products/DocumentManagement/HTMLParserNet.aspx

2. 使用实例1

[csharp]  view plain copy
  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.     }  
  120. }  

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

3. 使用实例2

[csharp]  view plain copy
  1. using Winista.Text.HtmlParser;  
  2.   
  3. using Winista.Text.HtmlParser.Tags;  
  4.   
  5. using Winista.Text.HtmlParser.Filters;  
  6.   
  7. using Winista.Text.HtmlParser.Util;  
  8.   
  9.             string str = "<table><tr><td>姓名</td><td>林肯</td></tr><tr><td>年龄</td><td>28</td></tr><tr><td>性别</td><td>男</td></tr><tr><td>姓名</td><td>克林顿</td></tr><tr><td>年龄</td><td>38</td></tr><tr><td>性别</td><td>男</td></tr></table>";  
  10.   
  11.             Parser parser = Parser.CreateParser( str , null );  
  12.   
  13.             NodeList nodes = parser.ExtractAllNodesThatMatch( new TagNameFilter("td") );  
  14.   
  15.             this.Page.Response.Write("<b>原来的html:</b>" + str  );  
  16.   
  17.             this.Page.Response.Write("<b>转换后的html:</b><br>" );  
  18.   
  19.             forint i = 5 ; i >= 0 ; i-- )  
  20.   
  21.             {  
  22.   
  23.                 this.Page.Response.Write( nodes[i*2].FirstChild.ToHtml() + nodes[i*2+1].FirstChild.GetText() + "<br>" );  
  24.   
  25.             }  


运行结果如下:

原来的html:

姓名林肯
年龄28
性别
姓名克林顿
年龄38
性别
转换后的html:

性别男

年龄38

姓名克林顿

性别男

年龄28

姓名林肯

0

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值