爬蟲淺談一:一個簡單c#爬蟲程序


這篇文章只是簡單展現一個基於HTTP請求如何抓取數據的文章,如以爲簡單的朋友,後續咱們再慢慢深刻研究探討。html

1web

 

 如圖1,咱們工做過程當中,不管平臺網站仍是企業官網,總少不了新聞展現。如某天產品經理跟咱們說,推廣人員想要抓取百度新聞中熱點要聞版塊提升站點百度排名。要抓取百度的熱點要聞版本,首先咱們先要了解站點https://news.baidu.com/請求頭(Request headers信息。正則表達式

爲何要了解請求頭(Request headers)信息? 算法

緣由是咱們能夠根據請求頭信息某部分報文信息假裝這是一個正常HTTP請求而不是人爲爬蟲程序躲過站點封殺,而成功獲取響應數據(Response datajson

 

如何查看百度新聞網址請求頭信息?瀏覽器

 2服務器

 

如圖2,咱們能夠打開谷歌瀏覽器或者其餘瀏覽器開發工具(按F12)查看該站點請求頭報文信息。從圖中能夠了解到該百度新聞站點能夠接受text/html等數據類型;語言是中文;瀏覽器版本是Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36等等報文信息,在咱們發起一個HTTP請求的時候直接攜帶該報文信息過去。固然並非每一個報文信息參數都必須攜帶過去,攜帶一部分可以請求成功便可。cookie

 

那什麼是響應數據(Response data)?app

3框架

 

如圖3,響應數據(Response data)是能夠從谷歌瀏覽器或者其餘瀏覽器中開發工具(按F12)查看到的,響應能夠是json數據,能夠是DOM樹數據,方便咱們後續解析數據。

 

固然您能夠學習任意一門開發語言開發爬蟲程序:C#NodeJsPythonJavaC++

但這裏主要講述是C#開發爬蟲程序。微軟爲咱們提供兩個關於HTTP請求HttpWebRequestHttpWebResponse對象,方便咱們發送請求獲取數據。如下展現下C# HTTP請求代碼:

        private string RequestAction(RequestOptions options)
        {
            string result = string.Empty;
            IWebProxy proxy = GetProxy();
            var request = (HttpWebRequest)WebRequest.Create(options.Uri);
            request.Accept = options.Accept;
            //在使用curl作POST的時候, 當要POST的數據大於1024字節的時候, curl並不會直接就發起POST請求, 而是會分爲倆步,
            //發送一個請求, 包含一個Expect: 100 -continue, 詢問Server使用願意接受數據
            //接收到Server返回的100 - continue應答之後, 才把數據POST給Server
            //並非全部的Server都會正確應答100 -continue, 好比lighttpd, 就會返回417 「Expectation Failed」, 則會形成邏輯出錯.
            request.ServicePoint.Expect100Continue = false;
            request.ServicePoint.UseNagleAlgorithm = false;//禁止Nagle算法加快載入速度
            if (!string.IsNullOrEmpty(options.XHRParams)) { request.AllowWriteStreamBuffering = true; } else { request.AllowWriteStreamBuffering = false; }; //禁止緩衝加快載入速度
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");//定義gzip壓縮頁面支持
            request.ContentType = options.ContentType;//定義文檔類型及編碼
            request.AllowAutoRedirect = options.AllowAutoRedirect;//禁止自動跳轉
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36";//設置User-Agent,假裝成Google Chrome瀏覽器
            request.Timeout = options.Timeout;//定義請求超時時間爲5秒
            request.KeepAlive = options.KeepAlive;//啓用長鏈接
            if (!string.IsNullOrEmpty(options.Referer)) request.Referer = options.Referer;//返回上一級歷史連接
            request.Method = options.Method;//定義請求方式爲GET
            if (proxy != null) request.Proxy = proxy;//設置代理服務器IP,假裝請求地址
            if (!string.IsNullOrEmpty(options.RequestCookies)) request.Headers[HttpRequestHeader.Cookie] = options.RequestCookies;
            request.ServicePoint.ConnectionLimit = options.ConnectionLimit;//定義最大鏈接數
            if (options.WebHeader != null && options.WebHeader.Count > 0) request.Headers.Add(options.WebHeader);//添加頭部信息
            if (!string.IsNullOrEmpty(options.XHRParams))//若是是POST請求,加入POST數據
            {
                byte[] buffer = Encoding.UTF8.GetBytes(options.XHRParams);
                if (buffer != null)
                {
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                ////獲取請求響應
                //foreach (Cookie cookie in response.Cookies)
                //    options.CookiesContainer.Add(cookie);//將Cookie加入容器,保存登陸狀態
                if (response.ContentEncoding.ToLower().Contains("gzip"))//解壓
                {
                    using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            result = reader.ReadToEnd();
                        }
                    }
                }
                else if (response.ContentEncoding.ToLower().Contains("deflate"))//解壓
                {
                    using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            result = reader.ReadToEnd();
                        }
                    }
                }
                else
                {
                    using (Stream stream = response.GetResponseStream())//原始
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            result = reader.ReadToEnd();
                        }
                    }
                }
            }
            request.Abort();
            return result;
        }
View Code

還有一個我自定義傳參對象,固然不管傳入或者傳出的對象都是大家根據本身實際業務需求定義的:

    public class RequestOptions
    {
        /// <summary>
        /// 請求方式,GET或POST
        /// </summary>
        public string Method { get; set; }
        /// <summary>
        /// URL
        /// </summary>
        public Uri Uri { get; set; }
        /// <summary>
        /// 上一級歷史記錄連接
        /// </summary>
        public string Referer { get; set; }
        /// <summary>
        /// 超時時間(毫秒)
        /// </summary>
        public int Timeout = 15000;
        /// <summary>
        /// 啓用長鏈接
        /// </summary>
        public bool KeepAlive = true;
        /// <summary>
        /// 禁止自動跳轉
        /// </summary>
        public bool AllowAutoRedirect = false;
        /// <summary>
        /// 定義最大鏈接數
        /// </summary>
        public int ConnectionLimit = int.MaxValue;
        /// <summary>
        /// 請求次數
        /// </summary>
        public int RequestNum = 3;
        /// <summary>
        /// 可經過文件上傳提交的文件類型
        /// </summary>
        public string Accept = "*/*";
        /// <summary>
        /// 內容類型
        /// </summary>
        public string ContentType = "application/x-www-form-urlencoded";
        /// <summary>
        /// 實例化頭部信息
        /// </summary>
        private WebHeaderCollection header = new WebHeaderCollection();
        /// <summary>
        /// 頭部信息
        /// </summary>
        public WebHeaderCollection WebHeader
        {
            get { return header; }
            set { header = value; }
        }
        /// <summary>
        /// 定義請求Cookie字符串
        /// </summary>
        public string RequestCookies { get; set; }
        /// <summary>
        /// 異步參數數據
        /// </summary>
        public string XHRParams { get; set; }
    }
View Code

根據展現的代碼,咱們能夠發現HttpWebRequest對象裏面都封裝了不少Request headers報文參數,咱們能夠根據該網站的Request headers信息在微軟提供的HttpWebRequest對象裏設置(看代碼報文參數註釋,都有寫相關參數說明,若是理解錯誤,望告之,謝謝),而後發送請求獲取Response data解析數據

 

還有補充一點,爬蟲程序可以使用代理IP最好使用代理IP,這樣下降被封殺機率,提升抓取效率。可是代理IP也分質量等級,對於某一些HTTPS站點,可能對應須要質量等級更加好的代理IP才能穿透,這裏暫不跑題,後續我會寫一篇關於代理IP質量等級文章詳說個人看法。

 C#代碼如何使用代理IP

 微軟NET框架也爲了咱們提供一個使用代理IP System.Net.WebProxy對象,關於使用代碼以下:

        private System.Net.WebProxy GetProxy()
        {
            System.Net.WebProxy webProxy = null;
            try
            {
                // 代理連接地址加端口
                string proxyHost = "192.168.1.1";
                string proxyPort = "9030";

                // 代理身份驗證的賬號跟密碼
                //string proxyUser = "xxx";
                //string proxyPass = "xxx";

                // 設置代理服務器
                webProxy = new System.Net.WebProxy();
                // 設置代理地址加端口
                webProxy.Address = new Uri(string.Format("{0}:{1}", proxyHost, proxyPort));
                // 若是隻是設置代理IP加端口,例如192.168.1.1:80,這裏直接註釋該段代碼,則不須要設置提交給代理服務器進行身份驗證的賬號跟密碼。
                //webProxy.Credentials = new System.Net.NetworkCredential(proxyUser, proxyPass);
            }
            catch (Exception ex)
            {
                Console.WriteLine("獲取代理信息異常", DateTime.Now.ToString(), ex.Message);
            }
            return webProxy;
        }
View Code

關於 System.Net.WebProxy對象參數說明,我在代碼裏面也作了解釋。

 

若是獲取到Response data數據是json,xml等格式數據,這類型解析數據方法咱們這裏就不詳細說了,請自行百度。這裏主要講的是DOMHTML數據解析,對於這類型數據有人會用正則表達式來解析,也有人用組件。固然只要能獲取到本身想要數據,怎麼解析都是能夠。這裏主要講我常常用到解析組件 HtmlAgilityPack,引用DLL爲(using HtmlAgilityPack)。解析代碼以下:

                HtmlDocument htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(simpleCrawlResult.Contents);
                HtmlNodeCollection liNodes = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='pane-news']").SelectSingleNode("div[1]/ul[1]").SelectNodes("li");
                if (liNodes != null && liNodes.Count > 0)
                {
                    for (int i = 0; i < liNodes.Count; i++)
                    {
                        string title = liNodes[i].SelectSingleNode("strong[1]/a[1]").InnerText.Trim();
                        string href = liNodes[i].SelectSingleNode("strong[1]/a[1]").GetAttributeValue("href", "").Trim();
                        Console.WriteLine("新聞標題:" + title + ",連接:" + href);
                    }
                }
View Code

另外附上HtmlAgilityPack學習連接 http://www.cnblogs.com/asxinyu/p/CSharp_HtmlAgilityPack_XPath_Weather_Data.html

 

下面主要展現抓取結果。

4

如圖4,抓取效果,一個簡單爬蟲程序就這樣子完成了。。。(這裏只是小弟不才我的看法,若有錯誤,望各位大牛多多指教)

相關文章
相關標籤/搜索