.net采集网页方法大全(5种)

/// <summary>方法一:比较推荐
        /// 用HttpWebRequest取得网页源码
        /// 对于带BOM的网页很有效,不管是什么编码都能正确识别
        /// </summary>
        /// <param name="url">网页地址" </param>


        /// <returns>返回网页源文件</returns>
        public static string GetHtmlSource2(string url,Encoding code)
        {
            //处理内容
            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)"; // 模拟使用IE在浏览
            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, code);
            html = reader.ReadToEnd();
            stream.Close();
            return html;
        }
 


        //方法二:
        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;
        }



        /// <summary>方法三:
        /// 
        /// </summary>
        /// <param name="url">/要访问的网站地址</param>
        /// <param name="charSets">目标网页的编码,如果传入的是null或者"",那就自动分析网页的编码</param>
        /// <returns></returns>
        public static string getHtml(string url, params  string[] charSets)
        {
            try
            {
                string charSet = null;
                if (charSets.Length == 1)
                {
                    charSet = charSets[0];
                }
                WebClient myWebClient = new WebClient(); //创建WebClient实例myWebClient
                // 需要注意的:
                //有的网页可能下不下来,有种种原因比如需要cookie,编码问题等等
                //这是就要具体问题具体分析比如在头部加入cookie
                // webclient.Headers.Add("Cookie", cookie);
                //这样可能需要一些重载方法.根据需要写就可以了
                //获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据.
                myWebClient.Credentials = CredentialCache.DefaultCredentials;
                //如果服务器要验证用户名,密码
                //NetworkCredential mycred = new NetworkCredential(struser, strpassword);
                //myWebClient.Credentials = mycred;
                //从资源下载数据并返回字节数组.(加@是因为网址中间有"/"符号)
                byte[] myDataBuffer = myWebClient.DownloadData(url);
                string strWebData = Encoding.Default.GetString(myDataBuffer);
                //获取网页字符编码描述信息
                Match charSetMatch = Regex.Match(strWebData, "<meta([^<]*)charset=([^<]*)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                string webCharSet = charSetMatch.Groups[2].Value;
                if (charSet == null || charSet == "")
                    charSet = webCharSet;
                if (charSet != null && charSet != "" && Encoding.GetEncoding(charSet) != Encoding.Default)
                {
                    strWebData = Encoding.GetEncoding(charSet).GetString(myDataBuffer);
                }
                else
                {
                    strWebData = Encoding.GetEncoding("utf-8").GetString(myDataBuffer);
                }
                return strWebData;
            }
            catch (Exception e) { return ""; }
        }

第4种:类似第2种,增加了代理功能


/// <summary>
    /// 远程获取数据
    /// </summary>
    /// <param name="url">url</param>
    /// <param name="code">编码</param>
    /// <param name="ProxyStr">代理IP,格式:10.20.30.40:8888</param>
    /// <returns></returns>
    public static string SendUrl(string url, Encoding code, string ProxyStr)
    {
        string html = string.Empty;
        //try
        //{
            HttpWebRequest WebReques = (HttpWebRequest)HttpWebRequest.Create(url);
            WebReques.Method = "GET";
            WebReques.Timeout = 20000;
            if (ProxyStr.Length > 0)
            {
                WebProxy proxy = new WebProxy(ProxyStr, true);
                WebReques.Proxy = proxy;
            }


            HttpWebResponse WebRespon = (HttpWebResponse)WebReques.GetResponse();
            if (WebRespon != null)
            {
                StreamReader sr = new StreamReader(WebRespon.GetResponseStream(), code);
                html = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                WebRespon.Close();
            }
        //}
        //catch
        //{


        //}
        return html;
    }

第5种:gzip

public string SendUrlGZIP(string PageUrl, System.Text.Encoding encode, string ProxyStr)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(PageUrl);
        if (ProxyStr.Length > 0)
        {
            WebProxy proxy = new WebProxy(ProxyStr, true);
            request.Proxy = proxy;
        }
        request.Headers.Add("Accept-Encoding", "gzip,deflate");
        request.AutomaticDecompression = DecompressionMethods.GZip;
        //request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; 
        WebResponse response = request.GetResponse();
        Stream resStream = response.GetResponseStream();
        Encoding enc = encode;
        StreamReader sr = new StreamReader(resStream, enc);
        string strHtml = sr.ReadToEnd();
        resStream.Close();
        sr.Close();
        return strHtml;
    }

原文发布于微信公众号 - 我为Net狂(dotNetCrazy)

原文发表时间:2016-09-07

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Jack的Android之旅

AsyncTask源码深入解析

最近想写一篇关于源码解析的文章,发现AsyncTask代码量不多,可里面的东西却是很值得学习的,所以故那这来“开刀”

902
来自专栏CodingBlock

Android查缺补漏(线程篇)-- AsyncTask的使用及原理详细分析

本文作者:CodingBlock 文章链接:http://www.cnblogs.com/codingblock/p/8515304.html

733
来自专栏mukekeheart的iOS之旅

Android基础总结(7)——异步消息处理

服务(Service)是Android中实现程序后台运行的解决方案,它非常适合用于去执行哪些不需要和用户交互而且还要长期运行的任务。服务的运行不依赖任何用户界...

2725
来自专栏Android 研究

Android Handler机制13之AsyncTask源码解析

AsyncTask是一个抽象类,我们需要创建子类去继承它,并且重写一些方法。AsyncTask接受三个泛型的参数:

811
来自专栏智能计算时代

IoTivitiy Architecture

IoTivity is an open source software framework enabling seamless device-to-device...

2774
来自专栏向治洪

android异步任务asyntask详解

在Android中实现异步任务机制有两种方式,Handler和AsyncTask。 Handler模式需要为每一个任务创建一个新的线程,任务完成后通过Han...

2088
来自专栏Phoenix的Android之旅

深入了解Android的Looper

Handler我们都知道,它需要和Looper绑定,当Handler在主线程创建,则会默认绑定主线程的Looper,当是在子线程创建,则需要在Handler的构...

791
来自专栏Phoenix的Android之旅

自带光环的HandlerThread

Thread之前说的多了,HandlerThread了解么,今天来说说他和Thread的区别

931
来自专栏AnitDDoS

防御各种DDoS反射的方法

1380
来自专栏刘望舒

AsyncTask源码解析

导语 AsyncTask对Android开发者来说并不陌生,当有耗时任务并涉及UI交互,AsyncTask可是处理异步任务的利器。AsyncTask使用也很方...

2135

扫码关注云+社区