日期:2014-05-17  浏览次数:20535 次

【正则表达式应用,提取html相应内容,莫名其妙的】
问题在下面的C# 注释,完整代码,可以直接黏贴在你们的机器运行,帮帮忙吧。搞了2天了,郁闷咯

  
    //过滤得到body里面的内容
    string regBody = "<body[^<>]*>(?:.|[\r\n])*</body>";

    //过滤得到class="searchresult_box"的div
    string regDiv = "<div[^<>]*class=\"searchresult_box\"+[^<>]*>(?:.|[\r\n])*</div>";

    //过滤得到id="flt_list"的div
    string regMainDiv = "<div.*[^<>]*.*id=\"flt_list\"+.*[^<>]*>(?:.|[\r\n])*</div>";
    protected void Button1_Click(object sender, EventArgs e)
    {
       
        string _strUrl = "http://www.wavin.cn/b.htm";
        // string _strUrl = "http://www.wavin.cn/c.htm";
        
        Regex regexDiv = new Regex(regDiv, RegexOptions.IgnoreCase);
        Regex regexBody = new Regex(regBody, RegexOptions.IgnoreCase);
        Regex regexMainDiv = new Regex(regMainDiv, RegexOptions.IgnoreCase);

        //这句正常,把body以外的内容都过滤掉了
        lalContent.Text = regexBody.Match(GetHtmlCode(_strUrl)).Value;

        //【【【【【【【【【【出错的地方】】】】】】】】】】】】
        //这句异常,不知道为何,当使用c.htm的源码时候就正常,看下面注释
        //lalContent.Text = regexDiv.Match(GetHtmlCode(_strUrl)).Value;

        /*
         *页面http://www.wavin.cn/b.htm 放的是完整的html,
         *而http://www.wavin.cn/c.htm 放的是body里面的一个id=flt_list的div、以及子div集合
         *大家可以分别看下2个页面的源码,
         */
    }
    

    /// <summary>
    /// 通过IP获取地区
    /// </summary>
    /// <param name="ip">ip地址</param>
    /// <returns></returns>
    public string GetHtmlCode(string url)
    {
        string area = "";
        Stream fs = null;
        StreamReader sr = null;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            fs = (System.IO.Stream)response.GetResponseStream();