前言:說到爬蟲,基本上清一色的都知道用Python,但是對於一些沒玩過或者不想玩Python的來說,卻比較頭大一點。所以以下我站在C# 的角度,來寫一個簡單的Demo,用來演示C# 實現的簡單小爬蟲。大家感興趣可以自己擴充出更加豐富的爬蟲功能。
前提:引用包HtmlAgilityPack
先來個爬取文字。
新建一個文字處理的方法,用於處理爬取的文字資料,並寫入到指定資料夾內的text.txt檔案內

static async Task ProcessText(HtmlDocument doc, string textDir)
{
var textNodes = doc.DocumentNode.SelectNodes("//*[text()]");
if (textNodes != null)
{
StringBuilder allText = new StringBuilder();
foreach (HtmlNode node in textNodes.Where(node => !string.IsNullOrWhiteSpace(node.InnerText)))
{
string textContent = WebUtility.HtmlDecode(node.InnerText.Trim());
if (!string.IsNullOrWhiteSpace(textContent))
{
allText.AppendLine(textContent);
}
}
string filePath = Path.Combine(textDir, "text.txt");
await File.WriteAllTextAsync(filePath, allText.ToString());
}
}
新增一個網頁處理方法,用於傳入網址進行抓取網頁資料,並傳給以上的文字處理方法進行解析文字資料,儲存到當前根目錄下的Texts資料夾內

以我兩天前寫的部落格內容為例,進行抓取。部落格地址為:https://www.cnblogs.com/weskynet/p/18213135

Main裡面呼叫有關方法,進行爬取。

說明:新增 User-Agent 頭部資訊可以幫助模擬常規的瀏覽器請求,避免被目標伺服器拒絕。
看下我當前的根目錄:

執行完畢,多出Texts資料夾

資料夾內多出程式裡面寫定的text.txt檔案

開啟文字檔案,可以看到文章全部內容,以及所有文字都被抓取下來了。

同文字處理,新增一個圖片處理方法:

static async Task ProcessImages(HtmlDocument doc, string baseUrl, string imagesDir)
{
var imageNodes = doc.DocumentNode.SelectNodes("//img[@src]");
if (imageNodes != null)
{
foreach (HtmlNode imageNode in imageNodes)
{
string imageUrl = imageNode.GetAttributeValue("src", null);
imageUrl = EnsureAbsoluteUrl(baseUrl, imageUrl);
string fileName = Path.GetFileName(new Uri(imageUrl).LocalPath);
string localPath = Path.Combine(imagesDir, fileName);
byte[] imageBytes = await client.GetByteArrayAsync(imageUrl);
await File.WriteAllBytesAsync(localPath, imageBytes);
}
}
}
網頁爬取方法裡面把文字有關改成圖片

以下是一個輔助方法,輔助方法用於處理相對URL,確保所有請求的URL是絕對的,防止資源載入失敗。
static string EnsureAbsoluteUrl(string baseUrl, string url) { return Uri.IsWellFormedUriString(url, UriKind.Absolute) ? url : new Uri(new Uri(baseUrl), url).AbsoluteUri; }
執行程式,執行完畢,根目錄下新增Images資料夾

資料夾內會看到該網址的所有圖片檔案。

圖片檔案格式都會被抓取,可以根據自己需要進行過濾。如果是整個站點,可以根據迴圈進行獲取每個頁面的資料。
最後再提供一個影片爬取的程式碼,由於沒找到可以爬取的站點,此處演示就不演示了,僅供程式碼出來給大家學習和技術分享使用。感興趣的大佬可以自行嘗試。

static async Task ProcessVideos(HtmlDocument doc, string baseUrl, string videosDir)
{
var videoNodes = doc.DocumentNode.SelectNodes("//video/source[@src]");
if (videoNodes != null)
{
foreach (HtmlNode videoNode in videoNodes)
{
string videoUrl = videoNode.GetAttributeValue("src", null);
videoUrl = EnsureAbsoluteUrl(baseUrl, videoUrl);
string videoName = Path.GetFileName(new Uri(videoUrl).LocalPath);
string videoPath = Path.Combine(videosDir, videoName);
byte[] videoBytes = await client.GetByteArrayAsync(videoUrl);
await File.WriteAllBytesAsync(videoPath, videoBytes);
}
}
}
如果大佬們想要直接獲取我本地測試的原始碼demo,可以在我的公眾號【Dotnet Dancer】後臺回覆:【爬蟲】 即可獲取我的本地demo原始碼自行除錯和把玩。
最近園子時不時會圖片全掛掉,如果圖片沒掉了,可以移步另一個地方圍觀:
https://mp.weixin.qq.com/s/NB2UWsfUdgNU82UVRbWe3Q
如果以上內容對你有幫助,歡迎關注我的公眾號【Dotnet Dancer】,或點贊、推薦和分享。我會時不時更新一些其他C#或者其他技術文章。