使用 C## 和 IronWebScraper 搜刮線上電影網站。

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

IronWebScraper 透過解析 HTML 元素、建立結構化資料儲存的類型化物件,以及使用元資料在頁面間導覽,從網站擷取電影資料,以建立全面的電影資訊資料集。 這個 C# Web Scraper 函式庫簡化了將非結構化網頁內容轉換為有組織、可分析資料的過程。

Quickstart: Scrape Movies in 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 類別有助於組織您的程式碼,並使其可重複使用。 此方法遵循物件導向原則,可讓您日後輕鬆擴充功能。

目標網站的結構是什麼樣子? 檢查網站結構是否有刮擦現象。 瞭解網站的結構對於有效的網路掃描至關重要。 與我們的 [Scraping from an Online Movie Website](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` 屬性,以供識別。

如何實作基本的影片掃描? 開始搜尋此資料集。 在執行任何 scraper 之前,請確保您已正確設定許可金鑰,如下所示: ```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"); } } } } ```

工作目錄屬性有何用途? 本代碼有哪些新內容? 工作目錄"屬性會設定所有 scraped 資料和相關檔案的主要工作目錄。 這可確保所有的輸出檔案都整理在單一位置,讓大規模的 scraping 專案更容易管理。 如果目錄不存在,將會自動建立。

何時應該使用 CSS 選擇器 vs 屬性? *其他注意事項:* 當透過結構位置或類別名稱鎖定元素時,CSS 選擇器是理想的選擇,而直接屬性存取則較適合抽取 ID 或自訂資料屬性等特定值。 在我們的範例中,我們使用 CSS 選擇器 (`#movie-featured > div`) 來瀏覽 DOM 結構,並使用屬性 (`data-movie-id`) 來擷取特定值。

如何為擷取的資料建立類型物件? 建立類型化的物件,以格式化的物件來保存 scraped 資料。 使用強式類型物件可提供更好的程式碼組織、IntelliSense 支援以及編譯時的類型檢查。 實作一個將持有格式化資料的 `Movie` class: ```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` 類別來保存 scraped 資料,提供類型安全和更好的程式碼組織。 2.我們將電影物件傳送至 `Scrape` 方法,該方法會瞭解我們的格式,並以定義的方式儲存,如下所示:

記事本視窗顯示 JSON 電影資料庫,包含結構化的電影資料,包括標題、URL 和 metadata 欄位

輸出內容會自動序列化為 JSON 格式,方便匯入資料庫或其他應用程式。

如何抓取詳細的電影頁面? 開始搜尋更詳細的網頁。 多頁面搜刮是常見的需求,IronWebScraper 透過其請求鏈機制,讓多頁面搜刮變得簡單直接。

我可以從詳細頁面中擷取哪些其他資料? 電影頁面是這樣的,包含每部電影的豐富元資料:

 related to 使用 C## 和 IronWebScraper 搜刮線上電影網站。