asp.Netデータ収集ベースクラス

19388 ワード

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; //     、COM、Microsoft   XML   ,   v2.6、  、  。
using System.Text.RegularExpressions;

    /// <summary>
    ///        
    /// </summary>
public class GetRemoteObj
{

    #region        
    public GetRemoteObj()
    {
        //
        // TODO:            
        //
    }
    ~GetRemoteObj()
    {
        Dispose();
    }
    #endregion

    #region IDisposable   

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }

    #endregion

    #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 = "";
        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);
        }
        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
", ""); 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; } #endregion }
        /**********************************
        *     :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