使用正则表达式获取页面指定div或table中内容

本人第一次使用正则表达式,在网上查找了很多关于取table和div中内容的表达式,但一大部分都是无用的。本人整理了下方便其他新手参考使用

工具: RegexText

步骤:第一步:获取内容使用HttpWebRequest和HttpWebResponse

      #region 以GET方式获取远程页面内容
 
    /****************************************
      * 函数名称:GetGetWeb
      * 功能说明:以GET方式获取远程页面内容
      * 参     数:url:HTML文本
      * 调用示列:
      *            string url = "http://www.actionforex.com/markets/data/currency-heat-map-2009031181561/";           
      *            string text = Tools.GetGetWeb(url,postData,encodeType);         
     *****************************************/
    /// <summary>
    /// 以GET方式获取远程页面内容
    /// </summary>
    /// <param name="url">页面url</param>
    /// <returns>页面内容</returns>
    public static string GetGetWeb(string url)
    {
        string content = "";
        try
        {
            System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            myRequest.Timeout = 19600;
            System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)myRequest.GetResponse();
            System.IO.Stream myStream = myResponse.GetResponseStream();
            System.IO.StreamReader sr = new System.IO.StreamReader(myStream, Encoding.Default);
            content = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            myStream.Close();
            myStream.Dispose();
        }
        catch (Exception ex)
        {
            content = ex.Message;
        }
        return content;
    }
 
    #endregion
 
第二  使用正则表达式获取需要的数据并清除数据中a标签和img标签
       /// <summary>
    /// 去除数据中标签
    /// </summary>
    /// <param name="html"></param>
    /// <returns></returns>
    public string ClearHtmlTag(string htmlText)
    {
        StringBuilder sbResult = new StringBuilder();
        string regex = "<div class=\"jwts_tabbertab\" title.*>[\\s\\S]*?</div>";
        MatchCollection matchList = Regex.Matches(htmlText, regex);
        foreach (Match item in matchList)
        {
            //去除a链接
            htmlText = Tools.ClearHtmlTag(item.Value, "a");
            //去除img标签
            htmlText = Tools.ClearHtmlTag(htmlText, "img");
            sbResult.Append(htmlText);
        }
        return sbResult.ToString();
    }
第三  删除数据中table中的列(本人方法是先把需要删除列中的数据清空在替换单元格为空)
        /// <summary>
    /// 对获取的数据进行处理
    /// </summary>
    /// <param name="htmlText">获取的html内容</param>
    /// <returns>处理后的html内容</returns>
    private string GetHandlerData(string htmlText)
    {
        htmlText = ClearHtmlTag(htmlText);
        //去除<th>Chart</th>列
        htmlText = htmlText.Replace("<th>Chart</th>", "");
        //<td class='sep'></td>列
        htmlText = htmlText.Replace("<td class='sep'></td>", "");
        string replaceValue = "<p>最后更新日期:{0}</p>";
        string regex = "<p>Last Updated:(.+?)</p>";
        htmlText = ModifyHtmlTextByRegex(htmlText, regex, replaceValue, ":");
        regex = "<p>Based on Bar of(.+?)</p>";
        replaceValue = "<p>基于截止时间 {0} 时段数据计算</p>";
        htmlText = ModifyHtmlTextByRegex(htmlText, regex, replaceValue, "f");
        return htmlText;
    }
 
第四  修改数据把伦敦时间变为北京时间
   
 
    /// <summary>
    /// 通过正则表达式修改伦敦时间
    /// </summary>
    /// <param name="htmlText">html内容</param>
    /// <param name="regex">正则表达式</param>
    /// <param name="replaceValue">替换的值</param>
    /// <param name="val">截取的值</param>
    /// <returns>html内容</returns>
    public string ModifyHtmlTextByRegex(string htmlText, string regex, string replaceValue, string val)
    {
        string localDateTime = string.Empty;
        string newValue = string.Empty;
        MatchCollection matchList = Regex.Matches(htmlText, regex);
        foreach (Match item in matchList)
        {
            localDateTime = DateTimeHandle(item.Value, val);
            newValue = string.Format(replaceValue, localDateTime);
            htmlText = htmlText.Replace(item.Value, newValue);
        }
        return htmlText;
    }
    
    /// <summary>
    /// 把伦敦时间转换为本地时间
    /// </summary>
    /// <param name="strTime"></param>
    /// <returns></returns>
    public string DateTimeHandle(string strTime, string val)
    {
        int startIndex = strTime.IndexOf(val) + 2;
        int lastIndex = strTime.LastIndexOf("GMT") - startIndex;
        strTime = strTime.Substring(startIndex, lastIndex).Trim();
        string[] strlist = strTime.Split(' ');
        strTime = DateTime.Now.Year + "/" + GetMonthNumber(strlist[0]) + "/" + strlist[1] + " " + strlist[2];
        strTime = Convert.ToDateTime(strTime).AddHours(8).ToString("yyyy年MM月dd日 hh:ss");
        return strTime;
    }
 
    /// <summary>
    /// 把大写月份转换数字类型
    /// </summary>
    /// <param name="month">大写月份</param>
    /// <returns>数字类型</returns>
    public int GetMonthNumber(string month)
    {
        switch (month)
        {
            case "Jan": return 1;
            case "Feb": return 2;
            case "Mar": return 3;
            case "Apr": return 4;
            case "May": return 5;
            case "Jun": return 6;
            case "Jul": return 7;
            case "Aug": return 8;
            case "Sep": return 9;
            case "Oct": return 10;
            case "Nov": return 11;
            case "Dec": return 12;
            default: return DateTime.Now.Month;
        }
    }
 
第五步 处理后的数据只是项目中使用的并使用动态页面输出供项目其他地方使用
    protected void Page_Load(object sender, EventArgs e)
    {
        //获取数据
        string htmlText = Tools.GetGetWeb(StandardPivotPoints);
        //处理后的数据
        htmlText = GetHandlerData(htmlText);
        Response.Write(htmlText);
    }
 
常用几个正则表达式

取出带有class和title属性的div标签内容的正则表达式
<div class=\"jwts_tabbertab\" title.*>[\s\S]*?</div>

取出带有class属性的table标签内容的正则表达式
<table class(.*)>.*?</table>

取出a标签的值和a标签中的内容

<td>(<a href.*?>(.*?)</a>)</td>

 

posted @ 2012-05-07 12:41  tiger longhu  阅读(3371)  评论(0编辑  收藏  举报