C#Xpath解析HtmlDocument的使用方法与递归取得页面所有标签xpath值(附源码)

在学习HTML Xpath之前呢我们先来下载一下Dll文件
下载地址:http://htmlagilitypack.codeplex.com/
大家下载单击如下图片下载就行了
<ignore_js_op>xpath1.jpg 

接下来就是在程序中引用一下,
<ignore_js_op>xpath2.jpg 
然后就可以直接调用 了,大家看看
代码吧

普通浏览 复制代码
  1.    //htmlDcoument对象用来访问Html文档s
  2.             HtmlAgilityPack.HtmlDocument hd =  new HtmlAgilityPack.HtmlDocument ( ) ;
  3.              //加载Html文档
  4.             hd.LoadHtml (strhtml ) ;
  5.    string str = hd.DocumentNode.SelectSingleNode ( "//*[@id='e_font']" ).OuterHtml ;


这样就可以得到一个标签的HTml代码了
OuterHtml是取包含本身的Html如果是InnerHtml就是取的包含在这个标签之内的所有Html代码了
这点大家要注意了
如果大家想获取Html代码的Xpath路径就是这部分

  1. //*[@id='e_font']
复制代码

这个其实很简单只在大家安装一个Firbug就行了,
看下图片
<ignore_js_op>xpath3.jpg 
大家只要进入选择模式,然后选择你要的内容,然后右键复制一下就行了。
然后放在SelectSingleNode()方法里就OK了
下面我说说几个方法和属性的意思吧、
方法


SelectNodes 获取的是一个集合
SelectSingleNode 获取一个标签
SetAttributeValue 设置标签的属性值例如:SetAttributeValue("name","xpath-89");这说明把name属性的值修改为xpath-89
属性


OuterHtml   是取包含本身的Html
InnerHtml   取的包含在这个标签之内的所有Html代码了
XPath   获取相对应的Xpath值
Attributes 获取一个属性的值例如:Attributes("name") 
也可以进行添加属性例如:

普通浏览 复制代码
  1. hd.DocumentNode.SelectSingleNode (item.Key ).Attributes.Add ( "xpathid""xpath_1"  ) ;



下面我写了一个递归获取Html页面所有Xpath值的方法大家看一下吧

普通浏览 复制代码
  1.    //key(Xpath),value(整个节点)
  2.          public List<ObjXpath> XpathList =  new List<ObjXpath> ( ) ;
  3.          public  string strhtml =  "" ; //这里就是你的Html代码具体怎么获取请参考我的<a href=\"http://www.sufeinet.com/thread-3-1-1.html\" target=\"_blank\">HttpHelper</a>类吧
  4.            private  int Index =  0 ;
  5. //开始处理Node
  6.          private  void SartNode ( )
  7.         {
  8.              //htmlDcoument对象用来访问Html文档s
  9.             HtmlAgilityPack.HtmlDocument hd =  new HtmlAgilityPack.HtmlDocument ( ) ;
  10.              //加载Html文档
  11.             hd.LoadHtml (strhtml ) ;
  12.             HtmlNodeCollection htmllist = hd.DocumentNode.ChildNodes ;
  13.             Index =  0 ;
  14.             XpathList.Clear ( ) ;
  15.              foreach  (HtmlNode em  in htmllist )
  16.             {
  17.                 Setxpath (em ) ;
  18.             }
  19.         }
  20.          /// <summary>
  21.          /// 递归获取Html Dom
  22.          /// </summary>
  23.          /// <param name="node">要处理的节点</param>
  24.          private  void Setxpath (HtmlNode node )
  25.         {
  26.              foreach  (HtmlNode item  in node.ChildNodes )
  27.             {
  28.                  if  (item. XPath.Contains ( "#" ) )
  29.                 {
  30.                      continue ;
  31.                 }
  32.                  if  (item.ChildNodes.Count >  0 )
  33.                 {
  34.                     XpathList.Add ( new ObjXpath ( ) { id = Index.ToString ( ), Key = item. XPath, Value =  "" } ) ;
  35.                     Index++ ;
  36.                     Setxpath (item ) ;
  37.                 }
  38.                  else
  39.                 {
  40.                     XpathList.Add ( new ObjXpath ( ) { id = Index.ToString ( ), Key = item. XPath, Value =  "" } ) ;
  41.                     Index++ ;
  42.                 }
  43.             }
  44.         }
  45.    public  class ObjXpath
  46.     {
  47.          public  string id { get ; set ; }
  48.          public  string Key { get ; set ; }
  49.          public  string Value { get ; set ; }
  50.     }


XpathList 就是获取的所有Xpath值了,大家有兴趣的话可以试试
我们先来看看效果吧
<ignore_js_op>xpath4.jpg 
好了下面放出所有代码给大家

普通浏览 复制代码
  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  System. Text. RegularExpressions ;
  10. using  System. Threading ;
  11. using HtmlAgilityPack ;
  12. using  System. IO ;
  13. using  System. Runtime. Serialization.Json ;
  14. namespace AutoXpathTools
  15. {
  16.      public partial  class Form1 : Form
  17.     {
  18.          public Form1 ( )
  19.         {
  20.             InitializeComponent ( ) ;
  21.         }
  22.          #region 私有变量和方法
  23.          //委托传入一个字符串
  24.          private  delegate  void SetListBox ( string str ) ;
  25.          //key(Xpath),value(整个节点)
  26.         List<ObjXpath> XpathList =  new List<ObjXpath> ( ) ;
  27.          private  int Index =  0 ;
  28.          //htmlDcoument对象用来访问Html文档
  29.         HtmlAgilityPack.HtmlDocument hd =  new HtmlAgilityPack.HtmlDocument ( ) ;
  30.          #endregion
  31.          //分析Xpath的所有代码
  32.          private  void btnGetXpath_Click ( object sender, EventArgs e )
  33.         {
  34.              try
  35.             {
  36.                 HttpHelper http =  new HttpHelper ( ) ;
  37.                 HttpItem item =  new HttpItem ( ) { URL = textBox1. Text.Trim ( ), IsToLower =  false, Encoding =  "gbk" } ;
  38.                 txtXml. Text = http.GetHtml (item ) ;
  39.                  if  (! string.IsNullOrWhiteSpace (txtXml. Text ) && txtXml. Text.Trim ( ).ToLower ( ) !=  "error" )
  40.                 {
  41.                      //加载Html文档
  42.                     hd.LoadHtml (txtXml. Text ) ;
  43.                   
  44.                     Thread pingTask =  new Thread ( new ThreadStart ( delegate
  45.                     {
  46.                          //代码,线程要执行的代码
  47.                         SartNode (txtXml. Text ) ;
  48.                     } ) ) ;
  49.                     pingTask.Start ( ) ;
  50.                    
  51.                 }
  52.                  else
  53.                 {
  54.                     txtXml. Text =  "根据您的的ULR:" + textBox1. Text.Trim ( ) +  "无法得到任何内容" ;
  55.                 }
  56.             }
  57.              catch  (Exception ex )
  58.             {
  59.                 txtXml. Text = ex.Message.Trim ( ) ;
  60.             }
  61.         }
  62.        
  63.          //开始处理Node
  64.          private  void SartNode ( string strhtml )
  65.         {
  66.              //htmlDcoument对象用来访问Html文档s
  67.             HtmlAgilityPack.HtmlDocument hd =  new HtmlAgilityPack.HtmlDocument ( ) ;
  68.              //加载Html文档
  69.             hd.LoadHtml (strhtml ) ;
  70.             HtmlNodeCollection htmllist = hd.DocumentNode.ChildNodes ;
  71.             Index =  0 ;
  72.             XpathList.Clear ( ) ;
  73.              foreach  (HtmlNode em  in htmllist )
  74.             {
  75.                 Setxpath (em ) ;
  76.             }
  77.         }
  78.          /// <summary>
  79.          /// 递归获取Html Dom
  80.          /// </summary>
  81.          /// <param name="node">要处理的节点</param>
  82.          private  void Setxpath (HtmlNode node )
  83.         {
  84.              foreach  (HtmlNode item  in node.ChildNodes )
  85.             {
  86.                  if  (item. XPath.Contains ( "#" ) )
  87.                 {
  88.                      continue ;
  89.                 }
  90.                  if  (item.ChildNodes.Count >  0 )
  91.                 {
  92.                     XpathList.Add ( new ObjXpath ( ) { id = Index.ToString ( ), Key = item. XPath, Value =  "" } ) ;
  93.                     UIContorol (item. XPath ) ;
  94.                     Index++ ;
  95.                     Setxpath (item ) ;
  96.                 }
  97.                  else
  98.                 {
  99.                     XpathList.Add ( new ObjXpath ( ) { id = Index.ToString ( ), Key = item. XPath, Value =  "" } ) ;
  100.                     UIContorol (item. XPath ) ;
  101.                     Index++ ;
  102.                 }
  103.             }
  104.         }
  105.       
  106.          //使用委托给控件赋值
  107.          private  void UIContorol ( string str )
  108.         {
  109.             listBox1.Items.Add (str ) ;
  110.             toolStripStatusLabel1. Text = str ;
  111.         }
  112.          private  void listBox1_SelectedValueChanged ( object sender, EventArgs e )
  113.         {
  114.              if  (listBox1.SelectedItem !=  null )
  115.             {
  116.                 txtPath. Text = listBox1.SelectedItem.ToString ( ).Trim ( ) ;
  117.             }
  118.         }
  119.          private  void button3_Click ( object sender, EventArgs e )
  120.         {
  121.             txtContents. Text = hd.DocumentNode.SelectSingleNode (txtPath. Text.Trim ( ) ).OuterHtml ;
  122.         }
  123.       
  124.          private  void Form1_Load ( object sender, EventArgs e )
  125.         {
  126.              //HttpItem item = new HttpItem()
  127.              //{
  128.              //    URL = "http://www.diandian.com/login",
  129.              //    Method = "post",
  130.              //    Cookie = "dtid=ZfXUVo1IsplHR4mHW1HYmgKbY4GJa003; kvf=1358855337188; alf=1; dru=1356356040; _l5=y",
  131.              //    ContentType = "application/x-www-form-urlencoded",
  132.              //    Postdata = "account=xinsuilie1998@163.com&password=wjlove520&nextUrl=&lcallback=&persistent=1",
  133.              //    Referer = "http://www.diandian.com/logout?formKey=e4714d863c862a84fafd83d98e5ecb22"
  134.              //};
  135.              //HttpHelper http = new HttpHelper();
  136.              //string html = http.GetHtml(item);
  137.              //string cookie = item.Cookie;
  138.              //item = new HttpItem() { URL = "http://www.diandian.com/home", Cookie = cookie };
  139.              //html = http.GetHtml(item);
  140.         }
  141.     }
  142.      public  class ObjXpath
  143.     {
  144.          public  string id { get ; set ; }
  145.          public  string Key { get ; set ; }
  146.          public  string Value { get ; set ; }
  147.     }
  148. }


就到这里吧,大家可以下载我的源代码试试手
打包下载:
<ignore_js_op> AutoXpathTools.zip (76.32 KB, 下载次数: 0) 
如果你感觉可以话就给我推荐一下吧。感谢大家

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值