C#とIronWebScraperを使用したオンライン映画サイトのスクレイピング
IronWebScraperは、HTML要素を解析してWebサイトから映画データを抽出し、型付きオブジェクトに構造化して格納します。さらに、メタデータを使ってページ間を移動し、映画情報をまとめたデータセットを構築します。このC#用Webスクレイパーライブラリを使うと、非構造化のWebコンテンツを分析しやすいデータに変換できます。
クイックスタート:C#で映画データをスクレイピング- NuGetパッケージマネージャーから
IronWebScraperをインストールします WebScraperを継承するクラスを作成します- ライセンスを設定し、対象URLをリクエストするために
Init()をオーバーライドします - CSSセレクタを使用して映画データを抽出するために
Parse()をオーバーライドします - JSON形式でデータを保存するには
Scrape()メソッドを使用します
-
1IronWebScraper を NuGet Package Manager でインストールします
-
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();Imports IronWebScraper Imports System Public Class QuickstartMovieScraper Inherits WebScraper Public Overrides Sub Init() ' Set your license key License.LicenseKey = "YOUR-LICENSE-KEY" ' Configure scraper settings Me.LoggingLevel = LogLevel.All Me.WorkingDirectory = "C:\MovieData\Output\" ' Start scraping from the homepage Me.Request("https://example-movie-site.com", AddressOf Parse) End Sub Public Overrides Sub Parse(response As Response) ' Extract movie titles using CSS selectors For Each movieDiv In response.Css(".movie-item") Dim title = movieDiv.Css("h2")(0).TextContentClean Dim url = movieDiv.Css("a")(0).Attributes("href") ' Save the scraped data Scrape(New With {Key .Title = title, Key .Url = url}, "movies.json") Next End Sub End Class ' Run the scraper Dim scraper As New QuickstartMovieScraper() scraper.Start()Imports IronWebScraper Imports System Public Class QuickstartMovieScraper Inherits WebScraper Public Overrides Sub Init() ' Set your license key License.LicenseKey = "YOUR-LICENSE-KEY" ' Configure scraper settings Me.LoggingLevel = LogLevel.All Me.WorkingDirectory = "C:\MovieData\Output\" ' Start scraping from the homepage Me.Request("https://example-movie-site.com", AddressOf Parse) End Sub Public Overrides Sub Parse(response As Response) ' Extract movie titles using CSS selectors For Each movieDiv In response.Css(".movie-item") Dim title = movieDiv.Css("h2")(0).TextContentClean Dim url = movieDiv.Css("a")(0).Attributes("href") ' Save the scraped data Scrape(New With {Key .Title = title, Key .Url = url}, "movies.json") Next End Sub End Class ' Run the scraper Dim scraper As New QuickstartMovieScraper() scraper.Start() -
3実際の環境でテストするためにデプロイする
今日からご自身のプロジェクトでIronWebScraperを使い始めるには、無料トライアルをお試しください。
映画データを収集するスクレイパークラスの作成
実際のWebサイトを例に、C#でのWebスクレイピングチュートリアルで紹介した手法を使って、映画サイトをスクレイピングします。
新しいクラスを追加し、それをMovieScraperと名付けます:
専用のスクレーパークラスを作成することで、コードを整理し、再利用可能にすることができます。 このアプローチは、オブジェクト指向の原則に従い、後で簡単に機能を拡張することができます。
ターゲットウェブサイトの構造はどのようになっていますか?
効率よくスクレイピングするには、対象サイトの構造を把握する必要があります。オンライン映画サイトからのスクレイピングのガイドと同様に、まずHTMLの構造を調べます。
どのHTML要素が映画データを含んでいますか?
次に示すのは、Webサイトのトップページの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>
映画ID、タイトル、詳細ページへのリンクを取得できます。各作品はクラスml-itemが付いたdiv要素で表され、一意のdata-movie-id属性で識別できます。
映画データの基本的なスクレイピング
このデータセットのスクレイピングを開始します。 スクレイパーを実行する前に、以下に示すようにライセンスキーが適切に設定されていることを確認してください:
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
End Sub
End ClassPublic 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
End Sub
End Classワーキングディレクトリプロパティは何のためのものですか?
このコードで追加した機能は何ですか?
Working Directoryプロパティは、すべてのスクレイピングデータと関連ファイルのメイン作業ディレクトリを設定します。 これにより、すべての出力ファイルが単一の場所に整理され、大規模なスクレイピングプロジェクトの管理が容易になります。 ディレクトリが存在しない場合は、自動的に作成されます。
CSSセレクターと属性のどちらをいつ使うべきですか?
その他の考慮事項
構造上の位置やクラス名で要素を選ぶにはCSSセレクターが適しています。IDやカスタムデータ属性などの値を取り出すには、属性に直接アクセスします。この例では、CSSセレクター(#movie-featured > div)でDOM構造をたどり、属性(data-movie-id)から値を取得します。
取得したデータを格納する型付きオブジェクトの作成
取得したデータは型付きオブジェクトに格納します。厳密に型付けすると、コードを整理しやすくなり、IntelliSenseの補完やコンパイル時の型チェックを利用できます。
構造化したデータを格納するMovieクラスを実装します。
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 ClassPublic Class Movie
Public Property Id As Integer
Public Property Title As String
Public Property URL As String
End Class型付きオブジェクトを使用するとデータの整理がどのように改善されますか?
コードを更新して、一般的なScrapedData辞書の代わりに型付きのMovieクラスを使用してください。
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(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
End Sub
End ClassPublic 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(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
End Sub
End Classスクレープメソッドは型付きオブジェクトにどの形式を使用しますか?
新機能は何ですか?
- 取得したデータを保持する
Movieクラスを実装しました。型安全性を確保し、コードを整理しやすくなります。 - 映画オブジェクトを
Scrapeメソッドに渡します。このメソッドはオブジェクトの形式を認識し、次のように所定の形式で保存します。
出力は自動的にJSON形式にシリアライズされるため、データベースや他のアプリケーションに簡単にインポートできます。
詳細な映画ページをスクレイピングする方法は?
続いて、映画の詳細ページをスクレイピングします。複数ページからデータを取得する場合は、IronWebScraperでリクエストを連鎖させると簡単に実装できます。
詳細ページから追加でどのようなデータを抽出できますか?
次の詳細ページには、作品ごとの詳しいメタデータが含まれています。
<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>
プロパティの追加による映画クラスの拡張
プロパティ(Description、Genre、Actor、Director、Country、Duration、IMDb Score)を追加してMovieクラスを拡張します。この例では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 ClassImports 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スクレイピング中にページ間を移動するにはどうすればよいですか?
詳細ページに移動してデータを取得します。IronWebScraperはスレッドセーフに動作するため、複数のページを並行して処理できます。
なぜ異なるページタイプに複数の解析関数を使用するのですか?
IronWebScraperでは、ページ形式ごとにスクレイピング関数を追加できます。処理の責務を分けることで、さまざまなページ構造に対応しやすくなり、コードの保守性も向上します。それぞれの解析関数は、特定の種類のページからのデータ抽出を担当します。
MetaDataはパース関数間でオブジェクトを渡すのにどう役立ちますか?
MetaData機能を使うと、リクエスト間で状態を維持できます。詳しくは高度なWebスクレイピング機能のガイドを参照してください。
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(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
End Sub
Public Sub ParseDetails(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
' 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
' Scrape and store detailed movie data
Scrape(movie, "Movie.Jsonl")
End Sub
End ClassPublic 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(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
End Sub
Public Sub ParseDetails(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
' 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
' Scrape and store detailed movie data
Scrape(movie, "Movie.Jsonl")
End Sub
End Class複数ページのスクレイピングの主な特徴
新機能は何ですか?
- ショッピングサイトからのスクレイピングと同様に、詳細ページを処理するスクレイピング関数(例:
ParseDetails)を追加します。 - ファイルを生成する
Scrape関数を新しい関数に移動し、すべての詳細が収集された後にのみデータが保存されることを確認します。 - IronWebScraperの
MetaData機能で映画オブジェクトを新しいスクレイピング関数に渡し、リクエスト間でオブジェクトの状態を維持します。 - ページをスクレイピングし、すべての情報がそろった映画オブジェクトのデータをファイルに保存します。
利用可能なメソッドとプロパティの詳細については、APIリファレンスを参照してください。 IronWebScraperは、ウェブサイトから構造化されたデータを抽出するための信頼できるフレームワークを提供し、データ収集と分析プロジェクトに不可欠なツールです。
よくある質問
C#でIronWebScraperは何に使用されますか?
IronWebScraperは、HTML要素を解析し構造化されたデータセットを作成することで、ウェブサイトからの映画データの抽出を行い、非構造的なウェブコンテンツを整理されたデータに変換するプロセスを大幅に簡素化します。
C#プロジェクトでIronWebScraperをどのようにインストールしますか?
IronWebScraperは、NuGetパッケージマネージャーを介してC#プロジェクトにインストールできます。これにより、Webスクレイピングタスクのためにプロジェクトに簡単に統合できます。
映画ウェブサイトをスクレイピングするために一般的に使用されるCSSセレクタはどれですか?
CSSセレクタは、映画ウェブサイトのHTML構造内で要素をナビゲートし選択するために使用されます。例えば、.movie-itemクラスは、タイトルやURLなどの情報を含むdivを選択するために使用されるかもしれません。
IronWebScraperはマルチページのスクレイピングに対応できますか?
はい、IronWebScraperはマルチページのスクレイピングに効率的に対応できます。リクエストチェーン機構を使用して異なるページ間を移動し、詳細なデータをスクレイピングします。
IronWebScraperで型付きオブジェクトを使用する利点は何ですか?
Movieクラスのような型付きオブジェクトを使用すると、よりよいコードの整理、IntelliSenseのサポートの向上、およびウェブサイトのデータをスクレイピングする際のコンパイル時の型チェックが可能になります。
映画ウェブサイトからスクレイピングしたデータをどのように整理できますか?
IronWebScraperのScrapeメソッドを使用して、スクレイピングしたデータをJSON形式に整理できます。これにより、構造化されたデータを管理可能で分析しやすい形式で保存することが助けになります。
`MetaData`機能はIronWebScraperでどのような役割を果たしますか?
IronWebScraperのMetaData機能は、リクエスト間でオブジェクトの状態を維持し、複数の解析関数間でデータを渡すことを可能にします。これは、マルチページスクレイピングで有用です。
なぜデータの抽出にIronWebScraperを選ぶのですか?
IronWebScraperは、マルチページのスクレイピング、型付きデータオブジェクト、詳細なAPIリファレンスなどの機能を提供し、効果的で効率的なウェブスクレイピングのための信頼性のあるフレームワークを提供するため、複雑なデータ収集プロジェクトに最適です。
IronWebScraperは出力ファイルの管理をどのように改善しますか?
IronWebScraperは作業ディレクトリを使用して、スクレイピング操作からのすべての出力ファイルを単一の事前定義された場所に整理することで管理を改善し、大規模なスクレイピングプロジェクトを容易にします。
IronWebScraperは詳細な映画ページから追加データをどのように抽出できますか?
IronWebScraperは、CSSセレクタやカスタムスクレイピング関数を使用して、映画の説明、ジャンル、主演者などの追加データを詳細な映画ページから抽出し、包括的なデータを収集できます。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。




