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);
            }
        }
    }
}
$vbLabelText   $csharpLabel

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

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

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

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

展望未來

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

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

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

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。

準備好開始了嗎?
Nuget 下載 128,072 | 版本: 2025.12 剛剛發布