如何在 C# 中從網站擷取資料

Curtis Chau
Curtis Chau
已更新: 2026年8月2日

IronWebScraper 是一個用於網頁抓取、網絡數據擷取和網絡內容解析的 .NET 程式庫。 這是一個易於使用的庫,可以添加到 Microsoft Visual Studio 專案中,用於開發和生產。

IronWebScraper 具有許多獨特的功能和能力,例如控制允許與禁止頁面、對象、媒體等。還可以管理多個身份、網頁緩存以及許多其他功能,我們會在本教程中介紹。

開始使用 IronWebScraper

立即在您的項目中開始使用 IronWebScraper,免費試用。

第一步:
arrow pointer

目標受眾

本教學課程針對具有基本或進階程式設計技能的軟體開發人員,他們希望建立和實現進階抓取功能(網站抓取、網站資料收集和提取、網站內容解析、網頁採集)的解決方案。

Webscraping 圖像

所需技能

  1. 具備基本的程式設計知識,熟練使用微軟程式語言之一,例如 C# 或 VB.NET。
  2. 對 Web 技術(HTML、JavaScript、jQuery、CSS 等)及其運作原理有基本的了解
  3. 具備 DOM、XPath、HTML 和 CSS 選擇器的基本知識

工具

  1. Microsoft Visual Studio 2010 或更高版本
  2. 適用於瀏覽器的 Web 開發人員擴充程序,例如 Chrome 的 Web Inspector 或 Firefox 的 Firebug。

為什麼要刮? (原因與概念)

如果您想打造一款具備以下功能的產品或解決方案:

  1. 提取網站資料
  2. 從多個網站比較內容、價格、功能等
  3. 掃描和快取網站內容

如果您有上述一個或多個原因,那麼 IronWebScraper 是符合您需求的出色程式庫

如何安裝 IronWebScraper?

在您Create a New Project後(見附錄A),您可以透過NuGet自動插入或手動安裝DLL來將IronWebScraper程式庫添加到您的專案中。

使用 NuGet 安裝

要通過NuGet將IronWebScraper程式庫添加到我們的專案中,我們可以使用視覺介面(NuGet套件管理器)或通過套件管理器主控台命令來完成。

使用 NuGet 套件管理器

  1. 使用滑鼠 -> 右鍵點選專案名稱 -> 選擇“管理 NuGet 套件”
  2. 從瀏覽標籤 -> 搜尋IronWebScraper -> 安裝
  3. 點選“確定”
  4. 完畢

使用 NuGet 套件控制台

  1. 從“工具”->“NuGet 套件管理器”->“套件管理器控制台”
  2. 選擇類別庫項目作為預設項目
  3. 執行命令 -> Install-Package IronWebScraper

手動安裝

  1. 前往 https://ironsoftware.com

  2. 點選IronWebScraper或直接使用URL https://ironsoftware.com/csharp/webscraper/訪問其頁面

  3. 點選下載 DLL。

  4. 解壓縮下載的壓縮文件

  5. 在 Visual Studio 中,以滑鼠右鍵按一下專案 -> 新增 -> 引用 -> 瀏覽

    使用DLL添加IronWebScraper

  6. 到解壓縮的資料夾 -> netstandard2.0 -> 並選擇所有.dll檔案

    使用DLL添加IronWebScraper 2

  7. 完成了!

HelloScraper - 我們的第一個 IronWebScraper 範例

像往常一樣,我們將首先實現 Hello Scraper 應用程式,並邁出使用 IronWebScraper 的第一步。

  • 我們已經創建了一個新控制台應用程式,名為“IronWebScraperSample”

建立 IronWebScraper 範例的步驟

  1. 創建一個資料夾,並命名為“HelloScraperSample”

  2. 然後新增一個類別並命名為HelloScraper HelloScraper 添加類別

  3. 將此程式碼片段添加到HelloScraper

    public class HelloScraper : WebScraper
    {
        /// <summary>
        /// Override this method to initialize your web scraper.
        /// Important tasks will be to request at least one start URL and set allowed/banned domain or URL patterns.
        /// </summary>
        public override void Init()
        {
            License.LicenseKey = "LicenseKey"; // Write License Key
            this.LoggingLevel = WebScraper.LogLevel.All; // Log all events
            this.Request("https://blog.scrapinghub.com", Parse); // Initialize a web request to the given URL
        }
    
        /// <summary>
        /// Override this method to create the default Response handler for your web scraper.
        /// If you have multiple page types, you can add additional similar methods.
        /// </summary>
        /// <param name="response">The HTTP Response object to parse</param>
        public override void Parse(Response response)
        {
            // Set working directory for the project
            this.WorkingDirectory = AppSetting.GetAppRoot() + @"\HelloScraperSample\Output\";
            // Loop on all links
            foreach (var titleLink in response.Css("h2.entry-title a"))
            {
                // Read link text
                string title = titleLink.TextContentClean;
                // Save result to file
                Scrape(new ScrapedData() { { "Title", title } }, "HelloScraper.json");
            }
    
            // Loop on all links for pagination
            if (response.CssExists("div.prev-post > a[href]"))
            {
                // Get next page URL
                var nextPage = response.Css("div.prev-post > a[href]")[0].Attributes["href"];
                // Scrape next URL
                this.Request(nextPage, Parse);
            }
        }
    }
  4. 現在要開始爬取,將此程式碼片段添加到Main

    static void Main(string[] args)
    {
        // Create Object From Hello Scrape class
        HelloScraperSample.HelloScraper scrape = new HelloScraperSample.HelloScraper();
        // Start Scraping
        scrape.Start();
    }
  5. 結果將保存為WebScraper.WorkingDirectory/classname.Json格式的檔案 HelloScraper 結果

程式碼概述

Scrape.Start()觸發爬取邏輯如下:

  1. 呼叫Init()方法以初始化變數、爬取屬性和行為屬性。
  2. 在Init()中設定起始頁面的請求,使用Request("https://blog.scrapinghub.com", Parse)。
  3. 並行處理多個 HTTP 請求和線程,保持程式碼同步,更易於偵錯。
  4. 在Init()後觸發Parse()方法,以利用CSS選擇器處理回應、提取資料並將其保存為JSON格式。

IronWebScraper 函式庫函數與選項

更新的文檔包含在使用手動安裝方法下載的zip檔案中(IronWebScraper Documentation.chm File),您也可以查看線上文檔以獲得程式庫的最新更新,網址為https://ironsoftware.com/csharp/webscraper/object-reference/。

要在您的專案中開始使用IronWebScraper,您必須從IronWebScraper.WebScraper類別繼承,這將擴展您的類別程式庫並添加爬取功能。 此外,您必須實作Init()和Parse(Response response)方法。

namespace IronWebScraperEngine
{
    public class NewsScraper : IronWebScraper.WebScraper
    {
        public override void Init()
        {
            throw new NotImplementedException();
        }

        public override void Parse(Response response)
        {
            throw new NotImplementedException();
        }
    }
}
屬性\函數類型描述
Init ()方法用於設定刮刀
Parse (Response response)方法用於實作爬蟲程式將使用的邏輯以及它將如何處理資料。 可以針對不同的頁面行為或結構實作多種方法。
BannedUrls, AllowedUrls, BannedDomains集合用於禁止/允許URL和/或域名。 例如:BannedUrls.Add("*.zip", "*.exe", "*.gz", "*.pdf");支持通配符和正則表達式。
ObeyRobotsDotTxt布林值用於啟用或禁用在robots.txt中讀取和遵循指令。
ObeyRobotsDotTxtForHost (string Host)方法用於啟用或禁用在特定域名中的robots.txt中讀取和遵循指令。
Scrape, ScrapeUnique方法
ThrottleMode枚舉Enum 選項:ByIpAddress, ByDomainHostName。 實現智慧請求限制,尊重主機 IP 位址或網域主機名稱。
EnableWebCache, EnableWebCache (TimeSpan cacheDuration)方法啟用網頁請求快取。
MaxHttpConnectionLimit國際設定允許開啟的 HTTP 請求(線程)總數。
RateLimitPerHostTimeSpan設定向給定網域或 IP 位址發出請求之間的最小禮貌延遲(暫停)。
OpenConnectionLimitPerHost國際設定每個主機名稱或 IP 位址允許的並發 HTTP 請求(執行緒)數量。
WorkingDirectory細繩設定用於儲存資料的工作目錄路徑。

真實案例與實踐

抓取線上電影網站

讓我們舉個例子,來抓取一個電影網站的資料。

新增一個類別並命名為MovieScraper:

新增MovieScraper類別

HTML結構

這是我們在網站首頁看到的HTML程式碼的一部分:

<div id="movie-featured" class="movies-list movies-list-full tab-pane in fade active">
    <div data-movie-id="20746" class="ml-item">
        <a href="https://website.com/film/king-arthur-legend-of-the-sword-20746/">
            <span class="mli-quality">CAM</span>
            <img data-original="https://img.gocdn.online/2017/05/16/poster/2116d6719c710eabe83b377463230fbe-king-arthur-legend-of-the-sword.jpg" 
                 class="lazy thumb mli-thumb" alt="King Arthur: Legend of the Sword"
                  src="https://img.gocdn.online/2017/05/16/poster/2116d6719c710eabe83b377463230fbe-king-arthur-legend-of-the-sword.jpg" 
                 style="display: inline-block;">
            <span class="mli-info"><h2>King Arthur: Legend of the Sword</h2></span>
        </a>
    </div>
    <div data-movie-id="20724" class="ml-item">
        <a href="https://website.com/film/snatched-20724/" >
            <span class="mli-quality">CAM</span>
            <img data-original="https://img.gocdn.online/2017/05/16/poster/5ef66403dc331009bdb5aa37cfe819ba-snatched.jpg" 
                 class="lazy thumb mli-thumb" alt="Snatched" 
                 src="https://img.gocdn.online/2017/05/16/poster/5ef66403dc331009bdb5aa37cfe819ba-snatched.jpg" 
                 style="display: inline-block;">
            <span class="mli-info"><h2>Snatched</h2></span>
        </a>
    </div>
</div>
HTML

我們可以看到,我們有電影 ID、標題和指向詳細頁面的連結。 讓我們開始抓取這些資料:

public class MovieScraper : WebScraper
{
    public override void Init()
    {
        License.LicenseKey = "LicenseKey";
        this.LoggingLevel = WebScraper.LogLevel.All;
        this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\";
        this.Request("www.website.com", Parse);
    }

    public override void Parse(Response response)
    {
        foreach (var div in response.Css("#movie-featured > div"))
        {
            if (div.GetAttribute("class") != "clearfix")
            {
                var movieId = div.GetAttribute("data-movie-id");
                var link = div.Css("a")[0];
                var movieTitle = link.TextContentClean;
                Scrape(new ScrapedData() { { "MovieId", movieId }, { "MovieTitle", movieTitle } }, "Movie.Jsonl");
            }
        }           
    }
}

結構化電影課程

為了存儲已格式化的數據,我們來實作一個電影類:

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }
}

現在更新我們的程式碼以使用Movie類別:

public class MovieScraper : WebScraper
{
    public override void Init()
    {
        License.LicenseKey = "LicenseKey";
        this.LoggingLevel = WebScraper.LogLevel.All;
        this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\";
        this.Request("https://website.com/", Parse);
    }

    public override void Parse(Response response)
    {
        foreach (var div in response.Css("#movie-featured > div"))
        {
            if (div.GetAttribute("class") != "clearfix")
            {
                var movie = new Movie
                {
                    Id = Convert.ToInt32(div.GetAttribute("data-movie-id")),
                    Title = div.Css("a")[0].TextContentClean,
                    URL = div.Css("a")[0].Attributes["href"]
                };
                Scrape(movie, "Movie.Jsonl");
            }
        }
    }
}

詳細頁面抓取

讓我們擴展我們的Movie類別,使之擁有新的屬性以獲得詳細資訊:

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }
    public string Description { get; set; }
    public List<string> Genre { get; set; }
    public List<string> Actor { get; set; }
}

然後導航到詳細資訊頁面,使用 IronWebScraper 的擴充功能進行抓取:

public class MovieScraper : WebScraper
{
    public override void Init()
    {
        License.LicenseKey = "LicenseKey";
        this.LoggingLevel = WebScraper.LogLevel.All;
        this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\";
        this.Request("https://domain/", Parse);
    }

    public override void Parse(Response response)
    {
        foreach (var div in response.Css("#movie-featured > div"))
        {
            if (div.GetAttribute("class") != "clearfix")
            {
                var movie = new Movie
                {
                    Id = Convert.ToInt32(div.GetAttribute("data-movie-id")),
                    Title = div.Css("a")[0].TextContentClean,
                    URL = div.Css("a")[0].Attributes["href"]
                };
                this.Request(movie.URL, ParseDetails, new MetaData() { { "movie", movie } });
            }
        }           
    }

    public void ParseDetails(Response response)
    {
        var movie = response.MetaData.Get<Movie>("movie");
        var div = response.Css("div.mvic-desc")[0];
        movie.Description = div.Css("div.desc")[0].TextContentClean;
        movie.Genre = div.Css("div > p > a").Select(element => element.TextContentClean).ToList();
        movie.Actor = div.Css("div > p:nth-child(2) > a").Select(element => element.TextContentClean).ToList();

        Scrape(movie, "Movie.Jsonl");
    }
}

IronWebScraper 庫功能

HttpIdentity 功能

某些系統要求使用者登入才能查看內容; 使用HttpIdentity作為憑證:

HttpIdentity id = new HttpIdentity
{
    NetworkUsername = "username",
    NetworkPassword = "pwd"
};
Identities.Add(id);

啟用 Web 快取

快取請求的頁面以便在開發過程中重複使用:

public override void Init()
{
    License.LicenseKey = "LicenseKey";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    EnableWebCache();
    this.Request("http://www.WebSite.com", Parse);
}

節流

控制連線數和速度:

public override void Init()
{
    License.LicenseKey = "LicenseKey";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    this.MaxHttpConnectionLimit = 80;
    this.RateLimitPerHost = TimeSpan.FromMilliseconds(50);
    this.OpenConnectionLimitPerHost = 25;
    this.ObeyRobotsDotTxt = false;
    this.ThrottleMode = Throttle.ByDomainHostName;
    this.Request("https://www.Website.com", Parse);
}

節流特性

  • MaxHttpConnectionLimit
    允許的開放HTTP請求(執行緒)的總數
  • RateLimitPerHost
    經過一定域名或IP地址的最小禮貌延遲(暫停)
  • OpenConnectionLimitPerHost
    每個主機或IP地址允許的並發HTTP請求(執行緒)數
  • ThrottleMode
    使WebScraper智能地限制請求不僅依據主機名,還依據主機服務器的IP地址。 如果多個被抓取的網域託管在同一台機器上,這樣做比較有禮貌。

附錄

如何建立 Windows 窗體應用程式?

請使用 Visual Studio 2013 或更高版本。

  1. 打開Visual Studio。
  2. 文件 -> 新建 -> 項目 Enterprise 2015
  3. 選擇 View C# 或 VB -> Windows -> Windows 窗體應用程式。 建立Windows應用程式

專案名稱: IronScraperSample
位置: 選擇您磁碟上的一個位置。

如何建立 ASP.NET Web 窗體應用程式?

  1. 打開Visual Studio。 Enterprise 2015
  2. 文件 -> 新建 -> 項目 檔案新專案
  3. 選擇 View C# 或 VB -> Web -> ASP.NET Web 應用程式 (.NET Framework)。 ASP .NET Web應用程式

專案名稱: IronScraperSample
位置: 選擇您磁碟上的一個位置。

  1. 從您的 ASP.NET 範本中,選擇一個空白範本並選取「Web 表單」。 ASP .NET樣板
  2. 您的基本 ASP.NET Web 表單專案已建立完成。 ASP .NET網頁表單專案

在此下載完整教程樣本專案代碼專案。

常見問題

什麼是IronWebScraper?

IronWebScraper是一個為網頁抓取、數據提取和網頁內容解析而設計的.NET 程式庫,可以整合到Microsoft Visual Studio專案中。

誰是C#網頁抓取教程的目標讀者?

該教程面向擁有基礎或高級編程技能的軟體開發者,這些開發者希望實現高級網頁抓取、數據收集和內容解析的解決方案。

跟隨C#網頁抓取教程需要什麼技能?

需要具備使用C#或VB.NET的基礎編程知識,了解HTML、JavaScript、JQuery、CSS等網絡技術,並熟悉DOM、XPath、HTML和CSS選擇器。

如何使用NuGet安裝IronWebScraper?

您可以通過在Visual Studio 的NuGet包管理器中搜索'IronWebScraper'並點擊安裝選項來安裝IronWebScraper。

'HelloScraper'應用在教程中的目的是什麼?

'HelloScraper'應用作為入門示例,讓用戶學習IronWebScraper的基本實施,展示數據提取和使用JSON格式保存的過程。

IronWebScraper可以處理多個網絡請求嗎,如何實現?

是的,IronWebScraper能夠並行處理多個HTTP請求和線程,允許更易於除錯的同步代碼。

IronWebScraper在處理HTTP身份時提供了哪些功能?

IronWebScraper提供了HttpIdentity功能,允許用戶指定網絡憑證,從而在需要身份驗證的網站上進行抓取。

IronWebScraper如何確保尊重服務器負載的友好網頁抓取?

IronWebScraper使用限制功能,例如MaxHttpConnectionLimit、RateLimitPerHost和OpenConnectionLimitPerHost進行請求速率管理,通過控制請求的速度和次數來確保友好和禮貌的抓取。

開發IronWebScraper時推薦使用哪些工具?

建議使用Microsoft Visual Studio 2010或以上版本,以及適用於Chrome的網頁檢查器或Firefox的Firebug等瀏覽器的網頁開發者擴展。

開發者如何擴展IronWebScraper的功能以滿足特定的數據提取需求?

開發者可以繼承IronWebScraper.WebScraper類來擴展功能,並通過覆寫Init()和Parse(Response response)等方法來實現自定義數據提取邏輯。

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

閱讀更多

準備好開始了嗎?

NuGet 下載次數 150,502版本:2026.11剛剛發布