使用 C## 和 IronWebScraper 抓取在线电影网站。

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

IronWebScraper 通过解析 HTML 元素、创建用于结构化数据存储的类型化对象以及使用元数据在页面间导航来建立全面的电影信息数据集,从而从网站中提取电影数据。 该 C# Web Scraper 库简化了将非结构化 Web 内容转换为有组织、可分析数据的过程。

as-heading:2(快速入门:用 C# 抓取电影)

1.通过 NuGet 软件包管理器安装 IronWebscraper 2.创建一个继承自 WebScraper 的类 3.覆盖 Init() 以设置许可证并请求目标 URL 4.覆盖 Parse() 以使用 CSS 选择器提取电影数据 5.使用 Scrape() 方法以 JSON 格式保存数据

Nuget Icon立即开始使用 NuGet 创建 PDF 文件:

  1. 使用 NuGet 包管理器安装 IronWebScraper

    PM > Install-Package IronWebScraper

  2. 复制并运行这段代码。

    using IronWebScraper;
    using System;
    
    public class QuickstartMovieScraper : WebScraper
    {
        public override void Init()
        {
            // Set your license key
            License.LicenseKey = "YOUR-LICENSE-KEY";
    
            // Configure scraper settings
            this.LoggingLevel = LogLevel.All;
            this.WorkingDirectory = @"C:\MovieData\Output\";
    
            // Start scraping from the homepage
            this.Request("https://example-movie-site.com", Parse);
        }
    
        public override void Parse(Response response)
        {
            // Extract movie titles using CSS selectors
            foreach (var movieDiv in response.Css(".movie-item"))
            {
                var title = movieDiv.Css("h2")[0].TextContentClean;
                var url = movieDiv.Css("a")[0].Attributes["href"];
    
                // Save the scraped data
                Scrape(new { Title = title, Url = url }, "movies.json");
            }
        }
    }
    
    // Run the scraper
    var scraper = new QuickstartMovieScraper();
    scraper.Start();
  3. 部署到您的生产环境中进行测试

    立即开始在您的项目中使用 IronWebScraper,免费试用!
    arrow pointer

如何设置 Movie Scraper 类? 从真实世界的网站示例开始。 我们将使用 [Webscraping in C#](https://ironsoftware.com/csharp/webscraper/tutorials/webscraping-in-c-sharp/) 教程中概述的技术来抓取一个电影网站。 添加一个新类并命名为 `MovieScraper`:

Visual Studio 添加新项目对话框,显示 IronScraperSample 项目的 Visual C# 模板选项

创建专用的 scraper 类有助于组织代码并使其可重复使用。 这种方法遵循面向对象的原则,使您以后可以轻松扩展功能。

目标网站结构是什么样的? 检查网站结构,以便进行刮擦。 了解网站结构对于有效的网络扫描至关重要。 与我们的[从在线电影网站抓取](https://ironsoftware.com/csharp/webscraper/how-to/scraping-from-an-online-movie-website/)指南类似,首先要分析 HTML 结构:

电影流网站界面,显示带有导航选项卡和质量指示器的电影海报网格

哪些 HTML 元素包含电影数据? 这是我们在网站上看到的主页 HTML 的一部分。检查 HTML 结构有助于确定要使用的正确 CSS 选择器: ```html ``` 我们有一个电影 ID、标题和详细页面的链接。 每部影片都包含在一个 `div` 元素中,该元素的类为 `ml-item` 并包含一个唯一的 `data-movie-id` 属性用于识别。

如何实现基本的电影抓取? 开始搜索该数据集。 在运行任何刮擦工具之前,请确保您已正确配置许可证密钥,如下所示: ```csharp public class MovieScraper : WebScraper { public override void Init() { // Initialize scraper settings License.LicenseKey = "LicenseKey"; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\"; // Request homepage content for scraping this.Request("www.website.com", Parse); } public override void Parse(Response response) { // Iterate over each movie div within the featured movie section foreach (var div in response.Css("#movie-featured > div")) { if (div.Attributes["class"] != "clearfix") { var movieId = Convert.ToInt32(div.GetAttribute("data-movie-id")); var link = div.Css("a")[0]; var movieTitle = link.TextContentClean; // Scrape and store movie data as key-value pairs Scrape(new ScrapedData() { { "MovieId", movieId }, { "MovieTitle", movieTitle } }, "Movie.Jsonl"); } } } } ```

工作目录属性有什么用? 本代码有哪些新内容? 工作目录 "属性为所有刮擦数据和相关文件设置了主要工作目录。 这样可以确保所有输出文件都组织在一个位置,从而更便于管理大规模的刮擦项目。 如果目录不存在,将自动创建。

何时应使用 CSS 选择器与属性? *其他注意事项:* CSS 选择器是通过结构位置或类名来定位元素的理想选择,而直接属性访问则更适合提取 ID 或自定义数据属性等特定值。 在我们的示例中,我们使用 CSS 选择器(`#movie-featured > div`)来浏览 DOM 结构,并使用属性(`data-movie-id`)来提取特定值。

如何为抓取的数据创建类型对象? 构建类型化对象,以格式化对象保存刮擦数据。 使用强类型对象可以提供更好的代码组织、IntelliSense 支持和编译时类型检查。 实现一个将保存格式化数据的 `Movie` 类: ```csharp public class Movie { public int Id { get; set; } public string Title { get; set; } public string URL { get; set; } } ```

使用类型对象如何改进数据组织? 更新代码以使用类型化的 `Movie` 类,而不是通用的 `ScrapedData` 字典: ```csharp public class MovieScraper : WebScraper { public override void Init() { // Initialize scraper settings License.LicenseKey = "LicenseKey"; this.LoggingLevel = WebScraper.LogLevel.All; this.WorkingDirectory = AppSetting.GetAppRoot() + @"\MovieSample\Output\"; // Request homepage content for scraping this.Request("https://website.com/", Parse); } public override void Parse(Response response) { // Iterate over each movie div within the featured movie section foreach (var div in response.Css("#movie-featured > div")) { if (div.Attributes["class"] != "clearfix") { var movie = new Movie { Id = Convert.ToInt32(div.GetAttribute("data-movie-id")) }; var link = div.Css("a")[0]; movie.Title = link.TextContentClean; movie.URL = link.Attributes["href"]; // Scrape and store movie object Scrape(movie, "Movie.Jsonl"); } } } } ```

Scrape 方法对类型对象使用什么格式? 最新消息? 1.我们实现了一个 `Movie` 类来保存刮擦数据,从而提供了类型安全性和更好的代码组织。 2.我们将电影对象传递给 `Scrape` 方法,该方法可理解我们的格式,并以定义的方式保存,如下所示:

记事本窗口显示 JSON 电影数据库,其中包含结构化的电影数据,包括标题、URL 和元数据字段

输出会自动序列化为 JSON 格式,便于导入数据库或其他应用程序。

如何抓取详细的电影页面? 开始抓取更详细的页面。 多页面抓取是一种常见需求,IronWebScraper 通过其请求链机制使其变得简单明了。

我可以从详细页面中提取哪些其他数据? 电影页面看起来是这样的,包含每部电影的丰富元数据:

 related to 使用 C## 和 IronWebScraper 抓取在线电影网站。