c#實(shí)現(xiàn)爬蟲程序

圖1
如圖1,我們工作過程中,無論平臺(tái)網(wǎng)站還是企業(yè)官網(wǎng),總少不了新聞?wù)故?。如某天產(chǎn)品經(jīng)理跟我們說,推廣人員想要抓取百度新聞中熱點(diǎn)要聞版塊提高站點(diǎn)百度排名。要抓取百度的熱點(diǎn)要聞版本,首先我們先要了解站點(diǎn)https://news.baidu.com/請(qǐng)求頭(Request headers)信息。
為什么要了解請(qǐng)求頭(Request headers)信息?
原因是我們可以根據(jù)請(qǐng)求頭信息某部分報(bào)文信息偽裝這是一個(gè)正常HTTP請(qǐng)求而不是人為爬蟲程序躲過站點(diǎn)封殺,而成功獲取響應(yīng)數(shù)據(jù)(Response data)。
如何查看百度新聞網(wǎng)址請(qǐng)求頭信息?

圖2
如圖2,我們可以打開谷歌瀏覽器或者其他瀏覽器開發(fā)工具(按F12)查看該站點(diǎn)請(qǐng)求頭報(bào)文信息。從圖中可以了解到該百度新聞?wù)军c(diǎn)可以接受text/html等數(shù)據(jù)類型;語言是中文;瀏覽器版本是Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36等等報(bào)文信息,在我們發(fā)起一個(gè)HTTP請(qǐng)求的時(shí)候直接攜帶該報(bào)文信息過去。當(dāng)然并不是每個(gè)報(bào)文信息參數(shù)都必須攜帶過去,攜帶一部分能夠請(qǐng)求成功即可。
那什么是響應(yīng)數(shù)據(jù)(Response data)?

圖3
如圖3,響應(yīng)數(shù)據(jù)(Response data)是可以從谷歌瀏覽器或者其他瀏覽器中開發(fā)工具(按F12)查看到的,響應(yīng)可以是json數(shù)據(jù),可以是DOM樹數(shù)據(jù),方便我們后續(xù)解析數(shù)據(jù)。
當(dāng)然您可以學(xué)習(xí)任意一門開發(fā)語言開發(fā)爬蟲程序:C#、NodeJs、Python、Java、C++。
但這里主要講述是C#開發(fā)爬蟲程序。微軟為我們提供兩個(gè)關(guān)于HTTP請(qǐng)求HttpWebRequest,HttpWebResponse對(duì)象,方便我們發(fā)送請(qǐng)求獲取數(shù)據(jù)。以下展示下C# HTTP請(qǐng)求代碼:
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的時(shí)候, 當(dāng)要POST的數(shù)據(jù)大于1024字節(jié)的時(shí)候, curl并不會(huì)直接就發(fā)起POST請(qǐng)求, 而是會(huì)分為倆步,
//發(fā)送一個(gè)請(qǐng)求, 包含一個(gè)Expect: 100 -continue, 詢問Server使用愿意接受數(shù)據(jù)
//接收到Server返回的100 - continue應(yīng)答以后, 才把數(shù)據(jù)POST給Server
//并不是所有的Server都會(huì)正確應(yīng)答100 -continue, 比如lighttpd, 就會(huì)返回417 “Expectation Failed”, 則會(huì)造成邏輯出錯(cuò).
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;//禁止自動(dòng)跳轉(zhuǎn)
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";//設(shè)置User-Agent,偽裝成Google Chrome瀏覽器
request.Timeout = options.Timeout;//定義請(qǐng)求超時(shí)時(shí)間為5秒
request.KeepAlive = options.KeepAlive;//啟用長(zhǎng)連接
if (!string.IsNullOrEmpty(options.Referer)) request.Referer = options.Referer;//返回上一級(jí)歷史鏈接
request.Method = options.Method;//定義請(qǐng)求方式為GET
if (proxy != null) request.Proxy = proxy;//設(shè)置代理服務(wù)器IP,偽裝請(qǐng)求地址
if (!string.IsNullOrEmpty(options.RequestCookies)) request.Headers[HttpRequestHeader.Cookie] = options.RequestCookies;
request.ServicePoint.ConnectionLimit = options.ConnectionLimit;//定義最大連接數(shù)
if (options.WebHeader != null && options.WebHeader.Count > 0) request.Headers.Add(options.WebHeader);//添加頭部信息
if (!string.IsNullOrEmpty(options.XHRParams))//如果是POST請(qǐng)求,加入POST數(shù)據(jù)
{
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())
{
////獲取請(qǐng)求響應(yīng)
//foreach (Cookie cookie in response.Cookies)
// options.CookiesContainer.Add(cookie);//將Cookie加入容器,保存登錄狀態(tài)
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;
}還有一個(gè)我自定義傳參對(duì)象,當(dāng)然無論傳入或者傳出的對(duì)象都是你們根據(jù)自己實(shí)際業(yè)務(wù)需求定義的:
public class RequestOptions
{
/// <summary>
/// 請(qǐng)求方式,GET或POST
/// </summary>
public string Method { get; set; }
/// <summary>
/// URL
/// </summary>
public Uri Uri { get; set; }
/// <summary>
/// 上一級(jí)歷史記錄鏈接
/// </summary>
public string Referer { get; set; }
/// <summary>
/// 超時(shí)時(shí)間(毫秒)
/// </summary>
public int Timeout = 15000;
/// <summary>
/// 啟用長(zhǎng)連接
/// </summary>
public bool KeepAlive = true;
/// <summary>
/// 禁止自動(dòng)跳轉(zhuǎn)
/// </summary>
public bool AllowAutoRedirect = false;
/// <summary>
/// 定義最大連接數(shù)
/// </summary>
public int ConnectionLimit = int.MaxValue;
/// <summary>
/// 請(qǐng)求次數(shù)
/// </summary>
public int RequestNum = 3;
/// <summary>
/// 可通過文件上傳提交的文件類型
/// </summary>
public string Accept = "*/*";
/// <summary>
/// 內(nèi)容類型
/// </summary>
public string ContentType = "application/x-www-form-urlencoded";
/// <summary>
/// 實(shí)例化頭部信息
/// </summary>
private WebHeaderCollection header = new WebHeaderCollection();
/// <summary>
/// 頭部信息
/// </summary>
public WebHeaderCollection WebHeader
{
get { return header; }
set { header = value; }
}
/// <summary>
/// 定義請(qǐng)求Cookie字符串
/// </summary>
public string RequestCookies { get; set; }
/// <summary>
/// 異步參數(shù)數(shù)據(jù)
/// </summary>
public string XHRParams { get; set; }
}根據(jù)展示的代碼,我們可以發(fā)現(xiàn)HttpWebRequest對(duì)象里面都封裝了很多Request headers報(bào)文參數(shù),我們可以根據(jù)該網(wǎng)站的Request headers信息在微軟提供的HttpWebRequest對(duì)象里設(shè)置(看代碼報(bào)文參數(shù)注釋,都有寫相關(guān)參數(shù)說明,如果理解錯(cuò)誤,望告之,謝謝),然后發(fā)送請(qǐng)求獲取Response data解析數(shù)據(jù)。
還有補(bǔ)充一點(diǎn),爬蟲程序能夠使用代理IP最好使用代理IP,這樣降低被封殺機(jī)率,提高抓取效率。但是代理IP也分質(zhì)量等級(jí),對(duì)于某一些HTTPS站點(diǎn),可能對(duì)應(yīng)需要質(zhì)量等級(jí)更加好的代理IP才能穿透,這里暫不跑題,后續(xù)我會(huì)寫一篇關(guān)于代理IP質(zhì)量等級(jí)文章詳說我的見解。
C#代碼如何使用代理IP?
微軟NET框架也為了我們提供一個(gè)使用代理IP 的System.Net.WebProxy對(duì)象,關(guān)于使用代碼如下:
private System.Net.WebProxy GetProxy()
{
System.Net.WebProxy webProxy = null;
try
{
// 代理鏈接地址加端口
string proxyHost = "192.168.1.1";
string proxyPort = "9030";
// 代理身份驗(yàn)證的帳號(hào)跟密碼
//string proxyUser = "xxx";
//string proxyPass = "xxx";
// 設(shè)置代理服務(wù)器
webProxy = new System.Net.WebProxy();
// 設(shè)置代理地址加端口
webProxy.Address = new Uri(string.Format("{0}:{1}", proxyHost, proxyPort));
// 如果只是設(shè)置代理IP加端口,例如192.168.1.1:80,這里直接注釋該段代碼,則不需要設(shè)置提交給代理服務(wù)器進(jìn)行身份驗(yàn)證的帳號(hào)跟密碼。
//webProxy.Credentials = new System.Net.NetworkCredential(proxyUser, proxyPass);
}
catch (Exception ex)
{
Console.WriteLine("獲取代理信息異常", DateTime.Now.ToString(), ex.Message);
}
return webProxy;
}關(guān)于 System.Net.WebProxy對(duì)象參數(shù)說明,我在代碼里面也做了解釋。
如果獲取到Response data數(shù)據(jù)是json,xml等格式數(shù)據(jù),這類型解析數(shù)據(jù)方法我們這里就不詳細(xì)說了,請(qǐng)自行百度。這里主要講的是DOM樹 HTML數(shù)據(jù)解析,對(duì)于這類型數(shù)據(jù)有人會(huì)用正則表達(dá)式來解析,也有人用組件。當(dāng)然只要能獲取到自己想要數(shù)據(jù),怎么解析都是可以。這里主要講我經(jīng)常用到解析組件HtmlAgilityPack,引用DLL為(using HtmlAgilityPack)。解析代碼如下:
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(simpleCrawlResult.Contents);
HtmlNodeCollection liNodes = htmlDoc.DocumentNode.SelectSingleNode("http://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("新聞標(biāo)題:" + title + ",鏈接:" + href);
}
}下面主要展示抓取結(jié)果。

圖4
如圖4,抓取效果,一個(gè)簡(jiǎn)單爬蟲程序就這樣子完成了。
到此這篇關(guān)于c#實(shí)現(xiàn)爬蟲程序的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
wpf將表中數(shù)據(jù)顯示到datagrid示例
這篇文章主要介紹了wpf將表中數(shù)據(jù)顯示到datagrid示例,需要的朋友可以參考下2014-02-02
C#使用DataSet Datatable更新數(shù)據(jù)庫的三種實(shí)現(xiàn)方法
這篇文章主要介紹了C#使用DataSet Datatable更新數(shù)據(jù)庫的三種實(shí)現(xiàn)方法,需要的朋友可以參考下2014-08-08
C#實(shí)現(xiàn)向數(shù)組指定索引位置插入新的元素值
這篇文章給大家介紹了利用C#實(shí)現(xiàn)向數(shù)組指定索引位置插入新的元素值,首先需要定義一個(gè)一維數(shù)組,然后修改數(shù)組的長(zhǎng)度,從而在其中增加一個(gè)元素,需要的朋友可以參考下2024-02-02

