1. 程式人生 > >關於C# 使用Xpath路徑(HtmlAgilityPack)對網頁內容查詢獲取的方法。(程式為.ashx的一般處理程式)

關於C# 使用Xpath路徑(HtmlAgilityPack)對網頁內容查詢獲取的方法。(程式為.ashx的一般處理程式)

先貼程式碼:

using System;
using System.Web;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace Lesson1
{
    /// <summary>
    /// ZZ_SY 的摘要說明
    /// </summary>
    public class ZZ_SY : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string url = context.Request["url"];
            int id = 0;
            
            #region id = 16  http://www.huadanseed.cn/huadan/ProductShow.asp?ID=169    Xpath 路徑在每個客戶端顯示不一樣
            if (id == 16)
            {
                string xpath_table = "//tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]"; 
                HtmlNodeCollection node_table = doc.DocumentNode.SelectSingleNode(xpath_table).ChildNodes;

                foreach (var node in node_table)
                {
                    if (node.InnerHtml.IndexOf("品種名稱") > 0)
                    {
                        string td = "td[2]";
                        var temp = node.SelectSingleNode(td);
                        temp = temp.SelectSingleNode("p");

                        data.nzname = temp.InnerText.Trim();
                    }

                    if (node.InnerHtml.IndexOf("公司名稱") > 0)
                    {

                        string td = "td[2]";
                        var temp = node.SelectSingleNode(td);
                        temp = temp.SelectSingleNode("p");

                        data.sccs = temp.InnerText.Trim();

                    }
                }
            }
            string JsonStr = JsonConvert.SerializeObject(data);
            context.Response.Write(JsonStr);

        }

         public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public class Entity
        {
            public string nzname;
            public string sccs;
        }
    }
}

主要問題在於 string xpath_table = "//tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]";

根據Postman 得到的 post 網頁內容,來分析如何設定 xpath_table

當設定 xpath_table = "//tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]" 時,

HtmlNodeCollection node_table = doc.DocumentNode.SelectSingleNode(xpath_table).ChildNodes;

上述程式碼中的作用是 獲取 <table[1]>,即<table width="90%" height="" border="1" align="center" cellpadding="1" ..> 包含的內容, 其中node_table 包含 13個items,其中的#text 內容在網頁上並不可見,只需通過所包含的漢字字串檢測得到所要查詢的 那一項   tr  即可。

        

獲取存在對應漢字的    tr  後,因為裡面包含兩個 td  , 因此要加字尾[2],來獲得 td[2]  中的內容,即 <p align="center" class="style7">小雜55</p>

,因為下一目錄只存在一個 <p> ,其中內容可以通過

var temp = node.SelectSingleNode(td);
data.nzname = temp.InnerText.Trim();

上述兩行程式碼直接獲取,作用和原始碼類似,(其實就多寫了一行程式碼而已)