如何在 C# 中从网站抓取数据

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

IronWebScraper是一个用于网页抓取、网路数据提取和网页内容解析的.NET库。 它是一个易于使用的库,可以添加到 Microsoft Visual Studio 项目中,用于开发和生产。

IronWebScraper具有许多独特的功能和能力,例如控制允许和禁止的页面、对象、媒体等。它还允许管理多个身份、网页缓存和许多其他功能,我们将在本教程中介绍。

开始使用IronWebScraper

从今天开始在您的项目中使用 IronWebScraper 免费试用。

第一步:
arrow pointer

目标受众

本教程针对具有基本或高级编程技能的软件开发人员,他们希望构建和实现高级抓取功能的解决方案(网站抓取、网站数据收集和提取、网站内容解析、网络捕获)。

网页抓取图像

所需技能

  1. 使用 Microsoft 编程语言(如 C# 或 VB.NET)的基本编程基础
  2. 对 Web 技术(HTML、JavaScript、JQuery、CSS 等)及其工作原理的基本理解
  3. 具备对 DOM、XPath、HTML 和 CSS 选择器的基本知识

工具

  1. Microsoft Visual Studio 2010 或更高版本
  2. 针对如 Chrome 浏览器的 web inspector 或 Firefox 的 Firebug 等浏览器的 Web 开发者扩展

为何进行抓取? (原因和概念)

如果你想构建具备以下功能的产品或解决方案:

  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. 现在要开始Scrape,将此代码片段添加到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. Parse()方法在Init()之后被触发,用于处理响应,使用CSS选择器提取数据并以JSON格式保存。

IronWebScraper 库功能和选项

更新的文档可以在使用手动安装方法下载的压缩文件中找到(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枚举枚举选项:ByIpAddress, ByDomainHostName. 启用智能请求限流,对主机 IP 地址或域名表现出尊重。
EnableWebCache, EnableWebCache (TimeSpan cacheDuration)方法启用 Web 请求缓存。
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. 选择 Visual C# 或 VB -> Windows -> Windows Forms 应用程序。 创建Windows应用程序

项目名称: IronScraperSample
位置: 在您的磁盘上选择一个位置。

如何创建 ASP.NET Web 窗体应用程序?

  1. 打开 Visual Studio。 Enterprise 2015
  2. 文件 -> 新建 -> 项目 文件新建项目
  3. 选择 Visual 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库,专为Web抓取、数据提取和Web内容解析而设计,可以集成到Microsoft Visual Studio项目中。

C# Web抓取教程的目标受众是谁?

该教程面向具备基础或高级编程技能的软件开发人员,旨在为他们提供解决方案以进行高级Web抓取、数据收集和内容解析。

跟随C# Web抓取教程需要哪些技能?

需要使用C#或VB.NET的编程基础知识,了解HTML、JavaScript、JQuery、CSS等Web技术,并熟悉DOM、XPath、HTML和CSS选择器。

如何通过NuGet安装IronWebScraper?

您可以在Visual Studio中的NuGet包管理器中搜索'IronWebScraper'并点击安装选项来安装IronWebScraper。

'HelloScraper'应用程序在教程中的目的是什么?

'HelloScraper'应用程序作为一个入门示例,帮助用户学习IronWebScraper的基本实现,演示了使用JSON格式的数据提取和保存。

IronWebScraper可以处理多个Web请求吗?怎么做?

是的,IronWebScraper能够处理多个HTTP请求和线程并行,从而允许更容易调试的同步代码。

IronWebScraper为处理HTTP身份提供了哪些功能?

IronWebScraper提供了HttpIdentity功能,使用户可以指定网络凭证,从而在需要身份验证的网站上进行抓取。

IronWebScraper如何确保礼貌的Web抓取以尊重服务器负载?

IronWebScraper使用限制功能如MaxHttpConnectionLimit、RateLimitPerHost和OpenConnectionLimitPerHost来管理请求速率,通过控制请求的速度和数量来确保礼貌和尊重的抓取。

与IronWebScraper一起开发推荐使用哪些工具?

建议使用Microsoft Visual Studio 2010或以上版本,以及用于浏览器的Web开发扩展,如Chrome的Web Inspector或Firefox的Firebug。

开发人员如何扩展IronWebScraper的功能以满足特定的数据提取需求?

开发人员可以继承IronWebScraper.WebScraper类以扩展功能,并通过重写Init()和Parse(Response response)方法实现自定义数据提取逻辑。

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

阅读更多

准备开始了吗?

NuGet 下载量 150,502版本:2026.11刚刚发布