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

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

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

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# 教學中概述的技術,刮取一個電影網站。

新增一個新類別並將其命名為MovieScraper

Visual Studio 新增項目對話框,顯示 IronScraperSample 專案的 Visual C# 模板選項

建立專用的 scraper 類別有助於組織您的程式碼,並使其可重複使用。 此方法遵循物件導向原則,可讓您日後輕鬆擴充功能。

目標網站的結構是什麼樣子?

檢查網站結構是否有刮擦現象。 瞭解網站的結構對於有效的網路掃描至關重要。 與我們的 Scraping from an Online Movie Website 指南類似,首先分析 HTML 結構:

電影串流網站介面,顯示電影海報網格,帶有導航標籤和品質指示器。

哪些 HTML 元素包含電影資料?

這是我們在網站上看到的首頁 HTML 的一部分。檢視 HTML 結構有助於找出要使用的正確 CSS 選擇器:

<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>
<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、標題和詳細頁面的連結。 每部影片都包含在 div 元件中,其類別為 ml-item 並包含唯一的 data-movie-id 屬性,以供識別。

如何實作基本的影片掃描?

開始搜尋此資料集。 在執行任何 scraper 之前,請確保您已正確設定許可金鑰,如下所示:

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");
            }
        }           
    }
}
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");
            }
        }           
    }
}
Public Class MovieScraper
	Inherits WebScraper

	Public Overrides Sub Init()
		' Initialize scraper settings
		License.LicenseKey = "LicenseKey"
		Me.LoggingLevel = WebScraper.LogLevel.All
		Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"

		' Request homepage content for scraping
		Me.Request("www.website.com", AddressOf Parse)
	End Sub

	Public Overrides Sub Parse(ByVal response As Response)
		' Iterate over each movie div within the featured movie section
		For Each div In response.Css("#movie-featured > div")
			If div.Attributes("class") <> "clearfix" Then
				Dim movieId = Convert.ToInt32(div.GetAttribute("data-movie-id"))
				Dim link = div.Css("a")(0)
				Dim movieTitle = link.TextContentClean

				' Scrape and store movie data as key-value pairs
				Scrape(New ScrapedData() From {
					{ "MovieId", movieId },
					{ "MovieTitle", movieTitle }
				},
				"Movie.Jsonl")
			End If
		Next div
	End Sub
End Class
$vbLabelText   $csharpLabel

工作目錄屬性有何用途?

本代碼有哪些新內容?

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

何時應該使用 CSS 選擇器 vs 屬性?

其他注意事項:

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

如何為擷取的資料建立類型物件?

建立類型化的物件,以格式化的物件來保存 scraped 資料。 使用強式類型物件可提供更好的程式碼組織、IntelliSense 支援以及編譯時的類型檢查。

實作一個將持有格式化資料的 Movie class:

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }
}
public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }
}
Public Class Movie
    Public Property Id As Integer
    Public Property Title As String
    Public Property URL As String
End Class
$vbLabelText   $csharpLabel

使用類型物件如何改善資料組織?

更新程式碼以使用類型化的 Movie 類別,而非一般的 ScrapedData 字典:

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");
            }
        }
    }
}
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");
            }
        }
    }
}
Public Class MovieScraper
	Inherits WebScraper

	Public Overrides Sub Init()
		' Initialize scraper settings
		License.LicenseKey = "LicenseKey"
		Me.LoggingLevel = WebScraper.LogLevel.All
		Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"

		' Request homepage content for scraping
		Me.Request("https://website.com/", AddressOf Parse)
	End Sub

	Public Overrides Sub Parse(ByVal response As Response)
		' Iterate over each movie div within the featured movie section
		For Each div In response.Css("#movie-featured > div")
			If div.Attributes("class") <> "clearfix" Then
				Dim movie As New Movie With {.Id = Convert.ToInt32(div.GetAttribute("data-movie-id"))}

				Dim link = div.Css("a")(0)
				movie.Title = link.TextContentClean
				movie.URL = link.Attributes("href")

				' Scrape and store movie object
				Scrape(movie, "Movie.Jsonl")
			End If
		Next div
	End Sub
End Class
$vbLabelText   $csharpLabel

Scrape 方法對於類型物件使用何種格式?

最新消息?
1.我們實作了一個 Movie 類別來保存 scraped 資料,提供類型安全和更好的程式碼組織。
2.我們將電影物件傳送至 Scrape 方法,該方法會瞭解我們的格式,並以定義的方式儲存,如下所示:

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

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

如何抓取詳細的電影頁面?

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

我可以從詳細頁面中擷取哪些其他資料?

電影頁面是這樣的,包含每部電影的豐富元資料:

 related to 我可以從詳細頁面中擷取哪些其他資料?<div class="mvi-content"> <div class="thumb mvic-thumb" style="background-image: url(https://img.gocdn.online/2017/04/28/poster/5a08e94ba02118f22dc30f298c603210-guardians-of-the-galaxy-vol-2.jpg);"></div> <div class="mvic-desc"> <h3>Guardians of the Galaxy Vol. 2</h3> <div class="desc"> Set to the backdrop of Awesome Mixtape #2, Marvel's Guardians of the Galaxy Vol. 2 continues the team's adventures as they travel throughout the cosmos to help Peter Quill learn more about his true parentage. </div> <div class="mvic-info"> <div class="mvici-left"> <p> <strong>Genre: </strong> <a href="https://Domain/genre/action/" title="Action">Action</a>, <a href="https://Domain/genre/adventure/" title="Adventure">Adventure</a>, <a href="https://Domain/genre/sci-fi/" title="Sci-Fi">Sci-Fi</a> </p> <p> <strong>Actor: </strong> <a target="_blank" href="https://Domain/actor/chris-pratt" title="Chris Pratt">Chris Pratt</a>, <a target="_blank" href="https://Domain/actor/-zoe-saldana" title="Zoe Saldana">Zoe Saldana</a>, <a target="_blank" href="https://Domain/actor/-dave-bautista-" title="Dave Bautista">Dave Bautista</a> </p> <p> <strong>Director: </strong> <a href="#" title="James Gunn">James Gunn</a> </p> <p> <strong>Country: </strong> <a href="https://Domain/country/us" title="United States">United States</a> </p> </div> <div class="mvici-right"> <p><strong>Duration:</strong> 136 min</p> <p><strong>Quality:</strong> <span class="quality">CAM</span></p> <p><strong>Release:</strong> 2017</p> <p><strong>IMDb:</strong> 8.3</p> </div> <div class="clearfix"></div> </div> <div class="clearfix"></div> </div> <div class="clearfix"></div> </div>

我應該如何擴展我的 Movie 類別以取得額外的屬性?

使用新的屬性擴充 Movie 類 (DescriptionGenreActorDirectorCountry)、Duration, IMDb Score) 但這個範例只使用 Description, Genre, 和 Actor. 對於類型和演員使用 List<string> 可以優雅地處理多重值:

using System.Collections.Generic;

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; }
}
using System.Collections.Generic;

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; }
}
Imports System.Collections.Generic

Public Class Movie
	Public Property Id() As Integer
	Public Property Title() As String
	Public Property URL() As String
	Public Property Description() As String
	Public Property Genre() As List(Of String)
	Public Property Actor() As List(Of String)
End Class
$vbLabelText   $csharpLabel

如何在 Scraping 時在頁面之間導覽?

導覽至詳細頁面以進行搜刮。 IronWebScraper 可自動處理 線程安全,允許同時處理多個頁面。

為何要針對不同的頁面類型使用多重解析函式?

IronWebScraper 可加入多種 scrape 功能,以處理不同的頁面格式。 這種關注點的分離使您的程式碼更具維護性,並允許適當處理不同的頁面結構。 每個解析功能都可以著重於從特定頁面類型中擷取資料。

元資料如何協助在解析函數之間傳遞物件?

MetaData 功能對於在不同的請求間維持狀態至關重要。 如需更多進階的網頁抓取功能,請查看我們的詳細指南:

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://domain/", 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"];

                // Request detailed page
                this.Request(movie.URL, ParseDetails, new MetaData() { { "movie", movie } });
            }
        }           
    }

    public void ParseDetails(Response response)
    {
        // Retrieve movie object from metadata
        var movie = response.MetaData.Get<Movie>("movie");
        var div = response.Css("div.mvic-desc")[0];

        // Extract description
        movie.Description = div.Css("div.desc")[0].TextContentClean;

        // Extract genres
        movie.Genre = new List<string>(); // Initialize genre list
        foreach(var genre in div.Css("div > p > a"))
        {
            movie.Genre.Add(genre.TextContentClean);
        }

        // Extract actors
        movie.Actor = new List<string>(); // Initialize actor list
        foreach (var actor in div.Css("div > p:nth-child(2) > a"))
        {
            movie.Actor.Add(actor.TextContentClean);
        }

        // Scrape and store detailed movie data
        Scrape(movie, "Movie.Jsonl");
    }
}
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://domain/", 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"];

                // Request detailed page
                this.Request(movie.URL, ParseDetails, new MetaData() { { "movie", movie } });
            }
        }           
    }

    public void ParseDetails(Response response)
    {
        // Retrieve movie object from metadata
        var movie = response.MetaData.Get<Movie>("movie");
        var div = response.Css("div.mvic-desc")[0];

        // Extract description
        movie.Description = div.Css("div.desc")[0].TextContentClean;

        // Extract genres
        movie.Genre = new List<string>(); // Initialize genre list
        foreach(var genre in div.Css("div > p > a"))
        {
            movie.Genre.Add(genre.TextContentClean);
        }

        // Extract actors
        movie.Actor = new List<string>(); // Initialize actor list
        foreach (var actor in div.Css("div > p:nth-child(2) > a"))
        {
            movie.Actor.Add(actor.TextContentClean);
        }

        // Scrape and store detailed movie data
        Scrape(movie, "Movie.Jsonl");
    }
}
Public Class MovieScraper
	Inherits WebScraper

	Public Overrides Sub Init()
		' Initialize scraper settings
		License.LicenseKey = "LicenseKey"
		Me.LoggingLevel = WebScraper.LogLevel.All
		Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"

		' Request homepage content for scraping
		Me.Request("https://domain/", AddressOf Parse)
	End Sub

	Public Overrides Sub Parse(ByVal response As Response)
		' Iterate over each movie div within the featured movie section
		For Each div In response.Css("#movie-featured > div")
			If div.Attributes("class") <> "clearfix" Then
				Dim movie As New Movie With {.Id = Convert.ToInt32(div.GetAttribute("data-movie-id"))}

				Dim link = div.Css("a")(0)
				movie.Title = link.TextContentClean
				movie.URL = link.Attributes("href")

				' Request detailed page
				Me.Request(movie.URL, AddressOf ParseDetails, New MetaData() From {
					{ "movie", movie }
				})
			End If
		Next div
	End Sub

	Public Sub ParseDetails(ByVal response As Response)
		' Retrieve movie object from metadata
		Dim movie = response.MetaData.Get(Of Movie)("movie")
		Dim div = response.Css("div.mvic-desc")(0)

		' Extract description
		movie.Description = div.Css("div.desc")(0).TextContentClean

		' Extract genres
		movie.Genre = New List(Of String)() ' Initialize genre list
		For Each genre In div.Css("div > p > a")
			movie.Genre.Add(genre.TextContentClean)
		Next genre

		' Extract actors
		movie.Actor = New List(Of String)() ' Initialize actor list
		For Each actor In div.Css("div > p:nth-child(2) > a")
			movie.Actor.Add(actor.TextContentClean)
		Next actor

		' Scrape and store detailed movie data
		Scrape(movie, "Movie.Jsonl")
	End Sub
End Class
$vbLabelText   $csharpLabel

此多頁面掃描方法的主要功能為何?

最新消息?

1.新增 scrape 功能 (例如:ParseDetails) 以 scrape 詳細頁面,類似於從購物網站scraping時使用的技術。
2.將產生檔案的 Scrape 函式移至新函式,確保在收集所有詳細資料後才儲存資料。
3.使用 IronWebScraper 功能(MetaData)將影片物件傳送至新的 scrape 函式,在不同的要求中維持物件狀態。
4.Scrape 頁面,並將影片物件資料儲存為資訊完整的檔案。

Notepad視窗顯示JSON電影資料庫,包含影片名稱、描述、URL和類型元資料

有關可用方法和屬性的詳細資訊,請參閱 API Reference。 IronWebScraper 為從網站擷取結構化資料提供了強大的框架,使其成為資料收集與分析專案中不可或缺的工具。

常見問題解答

如何使用 C# 從 HTML 擷取電影標題?

IronWebScraper 提供 CSS 選擇器方法來從 HTML 擷取電影標題。使用 response.Css() 方法與適當的選擇器,如 '.movie-item h2' 來鎖定標題元素,然後訪問 TextContentClean 屬性來取得乾淨的文字值。

在多個電影頁面之間導覽的最佳方式是什麼?

IronWebScraper 透過 Request() 方法處理頁面導覽。您可以使用 CSS 選擇器來擷取分頁連結,然後以每個 URL 來呼叫 Request(),從多個頁面中搜刮資料,自動建立全面的影片資料集。

如何將擷取的影片資料儲存為結構化格式?

使用 IronWebScraper 的 Scrape() 方法以 JSON 格式儲存資料。建立匿名物件或包含影片屬性(如標題、URL 和評分)的類型,然後將它們連同檔案名稱傳送給 Scrape(),以自動序列化並儲存資料。

我應該使用哪些 CSS 選擇器來擷取影片資訊?

IronWebScraper 支援標準 CSS 選擇器。對於電影網站,可使用'.movie-item「等選擇器來表示容器、」h2「表示標題、」a[href]'表示連結,以及特定的類別名稱來表示評級或類型。Css() 方法會返回您可以遍歷的集合。

如何處理 scraped 資料中的「CAM」等電影品質指標?

IronWebScraper 可讓您針對其特定的 HTML 元素,擷取並處理品質指標。使用 CSS 選擇器來定位品質徽章或文字,然後將它們作為屬性包含在您的 scraped 資料物件中,以獲得全面的電影資訊。

我可以為我的影片搜刮作業設定記錄嗎?

是的,IronWebScraper 包含內建的日誌功能。在 Init() 方法中將 LoggingLevel 屬性設定為 LogLevel.All,以追蹤所有的刮除活動、錯誤和進度,這有助於調試和監控您的影片資料擷取。

為 scraped data 設定工作目錄的正確方式是什麼?

IronWebScraper 可讓您在 Init() 方法中設定一個 WorkingDirectory 屬性。指定一個路徑,例如「C:\MovieData\Output\」,將擷取的影片資料檔案儲存於此。這可集中管理輸出,並讓您的資料井井有條。

如何正確繼承 WebScraper 類別?

創建一個繼承自 IronWebScraper 的 WebScraper 基類的新類。覆寫 Init() 方法進行設定,並覆寫 Parse() 方法進行資料擷取邏輯。這種面向物件的方法可讓您的影片搜刮程式可重複使用且易於維護。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 129,322 | 版本: 2026.2 剛剛發布