ASP.NET抓取网页内容的方法

一、ASP.NET 使用HttpWebRequest抓取网页内容


			
/**/             /// <summary>方法一:比较推荐
        /// 用HttpWebRequest取得网页源码
        /// 对于带BOM的网页很有效,不管是什么编码都能正确识别
        /// </summary>
        /// <param name="url">网页地址" </param>
        /// <returns>返回网页源文件</returns>
        public static string GetHtmlSource2(string url)
        {
            //处理内容
            string html = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "*/*"; //接受任意文件
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"; // 
            request.AllowAutoRedirect = true;//是否允许302
            //request.CookieContainer = new CookieContainer();//cookie容器,
            request.Referer = url; //当前页面的引用
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.Default);
            html = reader.ReadToEnd();
            stream.Close();
            return html;
        }

		



二、ASP.NET 使用 WebResponse 抓取网页内容


			
        public static string GetHttpData2(string Url)
        {
            string sException = null;
            string sRslt = null;
            WebResponse oWebRps = null;
            WebRequest oWebRqst = WebRequest.Create(Url);
            oWebRqst.Timeout = 50000;
            try
            {
                oWebRps = oWebRqst.GetResponse();
            }
            catch (WebException e)
            {
                sException = e.Message.ToString();
            }
            catch (Exception e)
            {
                sException = e.ToString();
            }
            finally
            {
                if (oWebRps != null)
                {
                    StreamReader oStreamRd = new StreamReader(oWebRps.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                    sRslt = oStreamRd.ReadToEnd();
                    oStreamRd.Close();
                    oWebRps.Close();
                }
            }
            return sRslt;
        }

		



参考资料: ASP.NET抓取网页内容  http://www.studyofnet.com/news/596.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值