轉載於:https://www.cnblogs.com/wzk153/p/9145684.html
HtmlAgilityPack相關詳解: https://www.cnblogs.com/asxinyu/p/CSharp_HtmlAgilityPack_XPath_Weather_Data.html
這篇文章只是簡單展示一個基於HTTP請求如何抓取數據的文章,如覺得簡單的朋友,后續我們再慢慢深入研究探討。
圖1:
如圖1,我們工作過程中,無論平台網站還是企業官網,總少不了新聞展示。如某天產品經理跟我們說,推廣人員想要抓取百度新聞中熱點要聞版塊提高站點百度排名。要抓取百度的熱點要聞版本,首先我們先要了解站點https://news.baidu.com/請求頭(Request headers)信息。
為什么要了解請求頭(Request headers)信息?
原因是我們可以根據請求頭信息某部分報文信息偽裝這是一個正常HTTP請求而不是人為爬蟲程序躲過站點封殺,而成功獲取響應數據(Response data)。
如何查看百度新聞網址請求頭信息?
圖2:
圖3:
如圖2,我們可以打開谷歌瀏覽器或者其他瀏覽器開發工具(按F12)=》點擊刷新 =》 點擊請求地址 (news.baidu.com) =》 查看該站點請求頭報文信息。從圖中可以了解到該百度新聞站點可以接受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請求的時候直接攜帶該報文信息過去。當然並不是每個報文信息參數都必須攜帶過去,攜帶一部分能夠請求成功即可。
那什么是響應數據(Response data)?
圖3:
如圖3,響應數據(Response data)是可以從谷歌瀏覽器或者其他瀏覽器中開發工具(按F12)查看到的,響應可以是json數據,可以是DOM樹數據,方便我們后續解析數據。
當然您可以學習任意一門開發語言開發爬蟲程序:C#、NodeJs、Python、Java、C++。
但這里主要講述是C#開發爬蟲程序。完整代碼如下:
using HtmlAgilityPack; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace ConsolePaCongApp3 { /// <summary> /// 自定義傳參對象,當然無論傳入或者傳出的對象都是你們根據自己實際業務需求定義的 /// </summary> 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; } } class Program { static void Main(string[] args) { var url = new Uri("http://news.baidu.com/");
//獲取到網頁的數據信息 var simpleCrawlResult = RequestAction(new RequestOptions() { Uri = url ,Method = "Get"}); HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(simpleCrawlResult); 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); } } HtmlNodeCollection liNodeItems = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='pane-news']").SelectNodes("ul/li"); if (liNodeItems != null && liNodeItems.Count > 0) { for (int i = 0; i < liNodeItems.Count; i++) { string title = liNodeItems[i].SelectSingleNode("a[1]").InnerText.Trim(); string href = liNodeItems[i].SelectSingleNode("a[1]").GetAttributeValue("href", "").Trim(); Console.WriteLine("新聞標題:" + title + ",鏈接:" + href); } } Console.Read(); } /// <summary> /// 微軟為我們提供兩個關於HTTP請求HttpWebRequest,HttpWebResponse對象,方便我們發送請求獲取數據。C# HTTP請求代碼: /// </summary> /// <param name="options"></param> /// <returns></returns> private static 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; } /// <summary> /// 微軟NET框架也為了我們提供一個使用代理IP 的System.Net.WebProxy對象 /// </summary> /// <returns></returns> private static 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; } } }
根據展示的代碼,我們可以發現HttpWebRequest對象里面都封裝了很多Request headers報文參數,我們可以根據該網站的Request headers信息在微軟提供的HttpWebRequest對象里設置(看代碼報文參數注釋,都有寫相關參數說明,如果理解錯誤,望告之,謝謝),然后發送請求獲取Response data解析數據。
還有補充一點,爬蟲程序能夠使用代理IP最好使用代理IP,這樣降低被封殺機率,提高抓取效率。但是代理IP也分質量等級,對於某一些HTTPS站點,可能對應需要質量等級更加好的代理IP才能穿透,這里暫不跑題,后續我會寫一篇關於代理IP質量等級文章詳說我的見解。
C#代碼如何使用代理IP?
微軟NET框架也為了我們提供一個使用代理IP 的System.Net.WebProxy對象,關於使用代碼如下:
/// <summary> /// 微軟NET框架也為了我們提供一個使用代理IP 的System.Net.WebProxy對象 /// </summary> /// <returns></returns> private static 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; }
關於 System.Net.WebProxy對象參數說明,我在代碼里面也做了解釋。
如果獲取到Response data數據是json,xml等格式數據,這類型解析數據方法我們這里就不詳細說了,請自行百度。這里主要講的是DOM樹 HTML數據解析,對於這類型數據有人會用正則表達式來解析,也有人用組件。當然只要能獲取到自己想要數據,怎么解析都是可以。這里主要講我經常用到解析組件 HtmlAgilityPack,引用DLL為(using HtmlAgilityPack)。解析代碼如下:
HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(simpleCrawlResult); 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); } } HtmlNodeCollection liNodeItems = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='pane-news']").SelectNodes("ul/li"); if (liNodeItems != null && liNodeItems.Count > 0) { for (int i = 0; i < liNodeItems.Count; i++) { string title = liNodeItems[i].SelectSingleNode("a[1]").InnerText.Trim(); string href = liNodeItems[i].SelectSingleNode("a[1]").GetAttributeValue("href", "").Trim(); Console.WriteLine("新聞標題:" + title + ",鏈接:" + href); } } Console.Read();
添加引用 =》項目右鍵 =》管理NuGet程序包 =》搜索HtmlAgilityPack 進行安裝
另外附上HtmlAgilityPack學習鏈接 http://www.cnblogs.com/asxinyu/p/CSharp_HtmlAgilityPack_XPath_Weather_Data.html
執行結果:
這里來分析下這行代碼:
HtmlNodeCollection liNodes = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='pane-news']").SelectSingleNode("div[1]/ul[1]").SelectNodes("li");
我們先分析下數據:
1:SelectSingleNode("//div[@id='pane-news']") ===》獲取id='pane-news'的div 內容 (紫色框部分)
2:SelectSingleNode("div[1]/ul[1]") ===》獲取 1中的第一個div標簽下的第一個ul內容 (綠色框部分)
3:SelectNodes("li") ===》獲取2中的所有li對象 (6個藍色框部分)
如果XPath的開頭是一個斜線(/)代表這是絕對路徑。如果開頭是兩個斜線(//)表示文件中所有符合模式的元素都會被選出來,即使是處於樹中不同的層級也會被選出來。以下的語法會選出文件中所有叫做cd的元素(在樹中的任何層級都會被選出來)://cd
htmlDoc.DocumentNode.SelectNodes("//ul/li"); (會把所有的ul下的li獲取出來)
如圖: