using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MSXML2;
using System.Text.RegularExpressions;
/// <summary>
/// ASP.NET數據採集封裝注意:記得添加引用 Interop.MSXML2.dll  不然msxml2命名空間用不了 COM組件Interop.MSXML2.dll則COM的引用列表中的Microsoft.xml v3.0 
/// </summary>
public class Search
{
    
        public Search()
        {
            //
            // TODO: 在此處添加構造函數邏輯
            //
        }
          public void Dispose() 
        { 
            GC.SuppressFinalize(this); 
        } 
      
        #region 日期隨機函數 
        /********************************** 
         * 函數名稱:DateRndName 
         * 功能說明:日期隨機函數 
         * 參    數:ra:隨機數 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          Random ra = new Random(); 
         *          string s = o.DateRndName(ra); 
         *          Response.Write(s); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 日期隨機函數 
        /// </summary> 
        /// <param name="ra">隨機數</param> 
        /// <returns></returns> 
        public string DateRndName(Random ra) 
        { 
            DateTime d = DateTime.Now; 
            string s = null, y, m, dd, h, mm, ss; 
            y = d.Year.ToString(); 
            m = d.Month.ToString(); 
            if (m.Length < 2) m = "0" + m; 
            dd = d.Day.ToString(); 
            if (dd.Length < 2) dd = "0" + dd; 
            h = d.Hour.ToString(); 
            if (h.Length < 2) h = "0" + h; 
            mm = d.Minute.ToString(); 
            if (mm.Length < 2) mm = "0" + mm; 
            ss = d.Second.ToString(); 
            if (ss.Length < 2) ss = "0" + ss; 
            s += y + m + dd + h + mm + ss; 
            s += ra.Next(100, 999).ToString(); 
            return s; 
        } 
        #endregion
        #region 取得文件後綴 
        /********************************** 
         * 函數名稱:GetFileExtends 
         * 功能說明:取得文件後綴 
         * 參    數:filename:文件名稱 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string url = @"http://www.baidu.com/img/logo.gif"; 
         *          string s = o.GetFileExtends(url); 
         *          Response.Write(s); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 取得文件後綴 
        /// </summary> 
        /// <param name="filename">文件名稱</param> 
        /// <returns></returns> 
        public string GetFileExtends(string filename) 
        { 
            string ext = null; 
            if (filename.IndexOf('.') > 0) 
            { 
                string[] fs = filename.Split('.'); 
                ext = fs[fs.Length - 1]; 
            } 
            return ext; 
        } 
        #endregion
        #region 獲取遠程文件源代碼 
        /********************************** 
         * 函數名稱:GetRemoteHtmlCode 
         * 功能說明:獲取遠程文件源代碼 
         * 參    數:Url:遠程url 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string url = @"http://www.baidu.com/"; 
         *          string s = o.GetRemoteHtmlCode(url); 
         *          Response.Write(s); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 獲取遠程文件源代碼 
        /// </summary> 
        /// <param name="url">遠程url</param> 
        /// <returns></returns> 
        public string GetRemoteHtmlCode(string Url) 
        {
            string s = "";
            try
            {               
                MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
                _xmlhttp.open("GET", Url, false, null, null);
                _xmlhttp.send("");
                if (_xmlhttp.readyState == 4)
                {
                    s = System.Text.Encoding.Default.GetString((byte[])_xmlhttp.responseBody);
                }
            }
            catch (Exception ex)
            {
                s = ex.Message+"指定的地址不存在或地址錯誤";
            }
            return s; 
        }
        #endregion
        #region 保存遠程文件 
        /********************************** 
         * 函數名稱:RemoteSave 
         * 功能說明:保存遠程文件 
         * 參    數:Url:遠程url;Path:保存到的路徑 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string s = ""; 
         *          string url = @"http://www.baidu.com/img/logo.gif"; 
         *          string path =Server.MapPath("Html/"); 
         *          s = o.RemoteSave(url,path); 
         *          Response.Write(s); 
         *          o.Dispose();          
         * ******************************/ 
        /// <summary> 
        /// 保存遠程文件 
        /// </summary> 
        /// <param name="Url">遠程url</param> 
        /// <param name="Path">保存到的路徑</param> 
        /// <returns></returns> 
        public string RemoteSave(string Url, string Path) 
        { 
            Random ra = new Random(); 
            string StringFileName = DateRndName(ra) + "." + GetFileExtends(Url); 
            string StringFilePath = Path + StringFileName; 
            MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass(); 
            _xmlhttp.open("GET", Url, false, null, null); 
            _xmlhttp.send(""); 
            if (_xmlhttp.readyState == 4) 
            { 
                if (System.IO.File.Exists(StringFilePath)) 
                    System.IO.File.Delete(StringFilePath); 
                System.IO.FileStream fs = new System.IO.FileStream(StringFilePath, System.IO.FileMode.CreateNew); 
                System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs); 
                w.Write((byte[])_xmlhttp.responseBody); 
                w.Close(); 
                fs.Close(); 
            } 
            else 
                throw new Exception(_xmlhttp.statusText); 
            return StringFileName; 
        } 
        #endregion 
  #region 替換網頁中的換行和引號 
        /********************************** 
         * 函數名稱:ReplaceEnter 
         * 功能說明:替換網頁中的換行和引號 
         * 參    數:HtmlCode:html源代碼 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string Url = @"http://www.baidu.com/"; 
         *          strion HtmlCode = o.GetRemoteHtmlCode(Url); 
         *          string s = o.ReplaceEnter(HtmlCode); 
         *          Response.Write(s); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 替換網頁中的換行和引號 
        /// </summary> 
        /// <param name="HtmlCode">HTML源代碼</param> 
        /// <returns></returns> 
        public string ReplaceEnter(string HtmlCode) 
        { 
            string s = ""; 
            if (HtmlCode == null || HtmlCode == "") 
                s = ""; 
            else 
                s = HtmlCode.Replace("\"", ""); 
            s = s.Replace("\r\n", ""); 
            return s; 
        }
        #endregion
        #region 執行正則提取出值 
        /********************************** 
         * 函數名稱:GetRegValue 
         * 功能說明:執行正則提取出值 
         * 參    數:HtmlCode:html源代碼 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string Url = @"http://www.baidu.com/"; 
         *          strion HtmlCode = o.GetRemoteHtmlCode(Url); 
         *          string s = o.ReplaceEnter(HtmlCode); 
         *          string Reg="<title>.+?</title>"; 
         *          string GetValue=o.GetRegValue(Reg,HtmlCode) 
         *          Response.Write(GetValue); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 執行正則提取出值 
        /// </summary> 
        /// <param name="RegexString">正則表達式</param> 
        /// <param name="RemoteStr">HtmlCode源代碼</param> 
        /// <returns></returns> 
        public string GetRegValue(string RegexString, string RemoteStr) 
        { 
            string MatchVale = ""; 
            Regex r = new Regex(RegexString); 
            Match m = r.Match(RemoteStr); 
            if (m.Success) 
            { 
                MatchVale = m.Value; 
            } 
            return MatchVale; 
        } 
        #endregion
        #region 替換HTML源代碼 
        /********************************** 
         * 函數名稱:RemoveHTML 
         * 功能說明:替換HTML源代碼 
         * 參    數:HtmlCode:html源代碼 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string Url = @"http://www.baidu.com/"; 
         *          strion HtmlCode = o.GetRemoteHtmlCode(Url); 
         *          string s = o.ReplaceEnter(HtmlCode); 
         *          string Reg="<title>.+?</title>"; 
         *          string GetValue=o.GetRegValue(Reg,HtmlCode) 
         *          Response.Write(GetValue); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 替換HTML源代碼 
        /// </summary> 
        /// <param name="HtmlCode">html源代碼</param> 
        /// <returns></returns> 
        public string RemoveHTML(string HtmlCode) 
        { 
            string MatchVale = HtmlCode; 
            foreach (Match s in Regex.Matches(HtmlCode, "<.+?>")) 
            { 
                MatchVale = MatchVale.Replace(s.Value, ""); 
            } 
            return MatchVale; 
        }
        #endregion
        #region 匹配頁面的連接 
        /********************************** 
         * 函數名稱:GetHref 
         * 功能說明:匹配頁面的連接 
         * 參    數:HtmlCode:html源代碼 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string Url = @"http://www.baidu.com/"; 
         *          strion HtmlCode = o.GetRemoteHtmlCode(Url); 
         *          string s = o.GetHref(HtmlCode); 
         *          Response.Write(s); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 獲取頁面的連接正則 
        /// </summary> 
        /// <param name="HtmlCode"></param> 
        /// <returns></returns> 
        public string GetHref(string HtmlCode) 
        { 
            string MatchVale = ""; 
            string Reg = @"(h|H)(r|R)(e|E)(f|F) *= *('|"")?((\w|\\|\/|\.|:|-|_)+)('|""| *|>)?"; 
            foreach (Match m in Regex.Matches(HtmlCode, Reg)) 
            { 
                MatchVale += (m.Value).ToLower().Replace("href=", "").Trim() + "||"; 
            } 
            return MatchVale; 
        } 
        #endregion
        #region 匹配頁面的圖片地址 
        /********************************** 
         * 函數名稱:GetImgSrc 
         * 功能說明:匹配頁面的圖片地址 
         * 參    數:HtmlCode:html源代碼;imgHttp:要補充的http.當好比:<img src="bb/x.gif">則要補充http://www.baidu.com/,當包含http信息時,則能夠爲空 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string Url = @"http://www.baidu.com/"; 
         *          strion HtmlCode = o.GetRemoteHtmlCode(Url); 
         *          string s = o.GetImgSrc(HtmlCode,"http://www.baidu.com/"); 
         *          Response.Write(s); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 匹配頁面的圖片地址 
        /// </summary> 
        /// <param name="HtmlCode"></param> 
        /// <param name="imgHttp">要補充的http://路徑信息</param> 
        /// <returns></returns> 
        public string GetImgSrc(string HtmlCode, string imgHttp) 
        { 
            string MatchVale = ""; 
            string Reg = @"<img.+?>"; 
            foreach (Match m in Regex.Matches(HtmlCode, Reg)) 
            { 
                MatchVale += GetImg((m.Value).ToLower().Trim(), imgHttp) + "||"; 
            } 
            return MatchVale; 
        } 
        /// <summary> 
        /// 匹配<img src="" />中的圖片路徑實際連接 
        /// </summary> 
        /// <param name="ImgString"><img src="" />字符串</param> 
        /// <returns></returns> 
        public string GetImg(string ImgString, string imgHttp) 
        { 
            string MatchVale = ""; 
            string Reg = @"src=.+\.(bmp|jpg|gif|png|)"; 
            foreach (Match m in Regex.Matches(ImgString.ToLower(), Reg)) 
            { 
                MatchVale += (m.Value).ToLower().Trim().Replace("src=", ""); 
            } 
            return (imgHttp + MatchVale); 
        }
        #endregion
        #region 替換經過正則獲取字符串所帶的正則首尾匹配字符串 
        /********************************** 
         * 函數名稱:GetHref 
         * 功能說明:匹配頁面的連接 
         * 參    數:HtmlCode:html源代碼 
         * 調用示例: 
         *          GetRemoteObj o = new GetRemoteObj(); 
         *          string Url = @"http://www.baidu.com/"; 
         *          strion HtmlCode = o.GetRemoteHtmlCode(Url); 
         *          string s = o.RegReplace(HtmlCode,"<title>","</title>"); 
         *          Response.Write(s); 
         *          o.Dispose(); 
         * ********************************/ 
        /// <summary> 
        /// 替換經過正則獲取字符串所帶的正則首尾匹配字符串 
        /// </summary> 
        /// <param name="RegValue">要替換的值</param> 
        /// <param name="regStart">正則匹配的首字符串</param> 
        /// <param name="regEnd">正則匹配的尾字符串</param> 
        /// <returns></returns> 
        public string RegReplace(string RegValue, string regStart, string regEnd) 
        { 
            string s = RegValue; 
            if (RegValue != "" && RegValue != null) 
            { 
                if (regStart != "" && regStart != null) 
                { 
                    s = s.Replace(regStart, ""); 
                } 
                if (regEnd != "" && regEnd != null) 
                { 
                    s = s.Replace(regEnd, ""); 
                } 
            } 
            return s; 
        }
        /********************************** 如下爲測試過的,在魏言項目裏使用的採集方法.按方法順序調用既可採集
        * 函數名稱:SniffwebCode 
        * 功能說明:得到頁面HTML代碼中開始標記和結束標記中間的數據:測試可用
        * 參    數:HTML源代碼 ,開始標記,結束標記
        * 調用示例: 
        *string url = @"http://sohe.inhe.net/Search/SearchingGuild.aspx"; 
        *string s = o.GetRemoteHtmlCode(url);//得到網站源碼
        *s=this.SniffwebCode(s,this.TextBox2.Text,this.TextBox3.Text);//得到指定HTML開始標記和結束標記中間的數據
        * ********************************/
        /// <summary>
        /// 得到HTML代碼開始標記和結束標記中間的數據
        /// </summary>
        /// <param name="code">HTML代碼</param>
        /// <param name="wordsBegin">開始標記</param>
        /// <param name="wordsEnd">結束標記</param>
        /// <returns></returns>
        public string SniffwebCode(string code, string wordsBegin, string wordsEnd)
        {
            string NewsTitle = "";
            Regex regex1 = new Regex("" + wordsBegin + @"(?<title>[\s\S]+?)" + wordsEnd + "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            for (Match match1 = regex1.Match(code); match1.Success; match1 = match1.NextMatch())
            {
                NewsTitle = match1.Groups["title"].ToString();
            }
            return NewsTitle;
        }
        /*** 調用例子 得到指定Html代碼中全部超級鏈接的標題和鏈接地址:測試有效 反回DataTable列說明:title 文字 url 地址
        *  string url = @"http://sohe.inhe.net/Search/SearchingGuild.aspx"; 
        *  string HtmlAllCode = o.GetRemoteHtmlCode(url);//得到網站全部源碼
        *  HtmlAllCode = o.SniffwebCode(HtmlAllCode, this.TextBox2.Text, this.TextBox3.Text);//根據開始標記和結束標記得到中間的數據
        *  DataTable table = o.GetCodeHref(HtmlAllCode);//得到指定Html全部超級鏈接的標題和鏈接地址返回一個DataTable表
        *  foreach(DataRow row in table.Rows)//循環表輸出標題和鏈接
        *  {
        *    Response.Write(row["title"]+"<br>");
        *    Response.Write(row["url"] + "<br>");
        *  }
        */
        /// <summary>
        /// 得到指定Html代碼中全部超級鏈接的標題和鏈接地址:測試有效 反回DataTable列說明:title 文字 url 地址
        /// </summary>
        /// <param name="HtmlCode">須要匹配出超級鏈接的HTML代碼</param>
        /// <returns></returns>
        public DataTable GetCodeHref(string HtmlCode)
        {
            //匹配指定HTML代碼中全部的超級鏈接中的href 和超鏈接文字內容的正則 有時候須要根據實際狀況作小調整若是標題中間有<B>文字</B>的話
            string regex = @"\<a.*href\s*=\s*(?:""(?<url>[^""]*)""|'(?<url>[^']*)'|(?<url>[^\>^\s]+)).*\>(?<title>[^\<^\>]*)\<[^\</a\>]*/a\>";
            Regex reg1 = new Regex(regex, RegexOptions.IgnoreCase);//建立正則表達式對象
            MatchCollection ms1 = reg1.Matches(HtmlCode);//根據正則表達式匹配出全部匹配項返匹配集合
            DataTable table = new DataTable();//建立存儲標題和鏈接的內存表
            table.Columns.Add("title");//標題文字列
            table.Columns.Add("url");//鏈接字符串
            foreach (Match m1 in ms1)//迭代集合得到每一個匹配項
            {
                DataRow row = table.NewRow();//建立一行
                row["title"] = m1.Groups["title"].Value.ToString();
                row["url"] = m1.Groups["url"].Value.ToString();
                table.Rows.Add(row);//添加入行集合
            }
            return table;
        }
        #endregion 
html