C# 中的網路爬蟲

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWebScraper是什麼?

IronWebScraper 是一個適用於 C# 和 .NET 程式設計平台的類別庫和框架,它允許開發人員以程式設計方式讀取網站並提取其內容。 這非常適合對網站或現有內網進行逆向工程,並將其轉換回資料庫或 JSON 資料。 它也可用於從互聯網下載大量文件。

在許多方面,Iron Web Scraper 與 Python 的 Scrapy 庫類似,但它利用了 C# 的優勢,特別是它能夠在網頁抓取過程中逐步執行程式碼並進行偵錯。

安裝

您的第一步是安裝 Iron Web Scraper,您可以從NuGet安裝,也可以從我們的網站下載 DLL 檔案

您需要的所有類別都可以在 Iron Web Scraper 命名空間中找到。

Install-Package IronWebScraper

常見應用案例

將網站遷移到資料庫

IronWebScraper 提供工具和方法,讓您可以將網站重新設計成結構化資料庫。 當舊網站和內部網路的內容遷移到新的 C# 應用程式時,這項技術非常有用。

網站遷移

能夠輕鬆地在 C# 中提取部分或完整網站的內容,可以減少遷移或升級網站和內網資源所需的時間和成本。 這比直接進行 SQL 轉換要高效得多,因為它將資料簡化為每個網頁上可見的內容,並且不需要理解先前的 SQL 資料結構,也不需要建立複雜的 SQL 查詢。

填充搜尋索引

Iron Web Scraper 可以指向您自己的網站或內網,讀取結構化數據,讀取每個頁面,並提取正確的數據,以便準確地填充您組織內的搜尋引擎。

IronWebScraper 是抓取內容以建立搜尋索引的理想工具。 像 IronSearch 這樣的搜尋應用程式可以從 IronWebScraper 讀取結構化內容,從而建立強大的企業搜尋系統。

使用鐵製刮刀

要學習如何使用 Iron Web Scraper,最好先查看範例。 這個基本範例創建了一個類,用於從網站部落格中抓取標題。

using IronWebScraper;

namespace WebScrapingProject
{
    class MainClass
    {
        public static void Main(string [] args)
        {
            var scraper = new BlogScraper();
            scraper.Start();
        }
    }

    class BlogScraper : WebScraper
    {
        // Initialize scraper settings and make the first request
        public override void Init()
        {
            // Set logging level to show all log messages
            this.LoggingLevel = WebScraper.LogLevel.All;

            // Request the initial page to start scraping
            this.Request("https://ironpdf.com/blog/", Parse);
        }

        // Method to handle parsing of the page response
        public override void Parse(Response response)
        {
            // Loop through each blog post title link found by CSS selector
            foreach (var title_link in response.Css("h2.entry-title a"))
            {
                // Clean and extract the title text
                string strTitle = title_link.TextContentClean;

                // Store the extracted title for later use
                Scrape(new ScrapedData() { { "Title", strTitle } });
            }

            // Check if there is a link to the previous post page and if exists, follow it
            if (response.CssExists("div.prev-post > a[href]"))
            {
                // Get the URL for the next page
                var next_page = response.Css("div.prev-post > a[href]")[0].Attributes["href"];

                // Request the next page to continue scraping
                this.Request(next_page, Parse);
            }
        }
    }
}
using IronWebScraper;

namespace WebScrapingProject
{
    class MainClass
    {
        public static void Main(string [] args)
        {
            var scraper = new BlogScraper();
            scraper.Start();
        }
    }

    class BlogScraper : WebScraper
    {
        // Initialize scraper settings and make the first request
        public override void Init()
        {
            // Set logging level to show all log messages
            this.LoggingLevel = WebScraper.LogLevel.All;

            // Request the initial page to start scraping
            this.Request("https://ironpdf.com/blog/", Parse);
        }

        // Method to handle parsing of the page response
        public override void Parse(Response response)
        {
            // Loop through each blog post title link found by CSS selector
            foreach (var title_link in response.Css("h2.entry-title a"))
            {
                // Clean and extract the title text
                string strTitle = title_link.TextContentClean;

                // Store the extracted title for later use
                Scrape(new ScrapedData() { { "Title", strTitle } });
            }

            // Check if there is a link to the previous post page and if exists, follow it
            if (response.CssExists("div.prev-post > a[href]"))
            {
                // Get the URL for the next page
                var next_page = response.Css("div.prev-post > a[href]")[0].Attributes["href"];

                // Request the next page to continue scraping
                this.Request(next_page, Parse);
            }
        }
    }
}
Imports IronWebScraper

Namespace WebScrapingProject
	Friend Class MainClass
		Public Shared Sub Main(ByVal args() As String)
			Dim scraper = New BlogScraper()
			scraper.Start()
		End Sub
	End Class

	Friend Class BlogScraper
		Inherits WebScraper

		' Initialize scraper settings and make the first request
		Public Overrides Sub Init()
			' Set logging level to show all log messages
			Me.LoggingLevel = WebScraper.LogLevel.All

			' Request the initial page to start scraping
			Me.Request("https://ironpdf.com/blog/", AddressOf Parse)
		End Sub

		' Method to handle parsing of the page response
		Public Overrides Sub Parse(ByVal response As Response)
			' Loop through each blog post title link found by CSS selector
			For Each title_link In response.Css("h2.entry-title a")
				' Clean and extract the title text
				Dim strTitle As String = title_link.TextContentClean

				' Store the extracted title for later use
				Scrape(New ScrapedData() From {
					{ "Title", strTitle }
				})
			Next title_link

			' Check if there is a link to the previous post page and if exists, follow it
			If response.CssExists("div.prev-post > a[href]") Then
				' Get the URL for the next page
				Dim next_page = response.Css("div.prev-post > a[href]")(0).Attributes("href")

				' Request the next page to continue scraping
				Me.Request(next_page, AddressOf Parse)
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

為了抓取特定網站的數據,我們需要建立一個自訂類別來讀取該網站的內容。這個類別將繼承自 Web Scraper 類別。 我們將向該類別添加一些方法,包括Init ,我們可以在其中設定初始設定並啟動第一個請求,這將引發連鎖反應,從而抓取整個網站。

我們還必須添加至少一個Parse方法。 解析方法讀取從互聯網下載的網頁,並使用類似 jQuery 的 CSS 選擇器來選擇內容,並提取相關的文字和/或圖像以供使用。

Parse方法中,我們還可以指定我們希望爬蟲繼續追蹤哪些超鏈接,以及它將忽略哪些超連結。

我們可以使用 Scrape 方法提取任何數據,並將其轉儲為方便的 JSON 樣式文件格式,以便以後使用。

展望未來

要了解有關 Iron Web Scraper 的更多信息,我們建議您閱讀API 參考文檔,然後開始查看我們文檔教學部分中的範例。

接下來我們推薦您查看的C#"部落格"網路爬蟲範例,我們將學習如何從部落格(例如 WordPress 部落格)中提取文字內容。 這在網站遷移中可能非常有用。

從那裡,您可以繼續查看其他高級網路爬蟲教學範例,我們可以了解諸如具有許多不同類型頁面的網站、電子商務網站等概念,以及如何在從互聯網抓取資料時使用多個代理、身分和登入。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。

準備好開始了嗎?
Nuget 下載 125,527 | Version: 2025.11 剛發表