C#でWebサイトからデータをスクレイピングする方法
IronWebScraperはウェブスクレイピング、ウェブデータ抽出、ウェブコンテンツ解析のための.NETライブラリです。 これは、開発と生産において使用するためにMicrosoft Visual Studioプロジェクトに追加できる使いやすいライブラリです。
IronWebScraperは多くのユニークな機能と能力を持ち、許可または禁止されたページ、オブジェクト、メディアなどを管理でき、複数のアイデンティティ、ウェブキャッシュ、そしてこのチュートリアルで取り扱う多くの他の機能の管理も可能です。
IronWebScraperで始めましょう
無料トライアルで今日からプロジェクトにIronWebScraperを使用し始めましょう。
対象読者
このチュートリアルは、ウェブスクレイピング機能のためのソリューションを構築および実装したい基本または高度なプログラミングスキルを持つソフトウェア開発者を対象としています(ウェブサイトのスクレイピング、ウェブサイトデータの収集と抽出、ウェブサイトコンテンツの解析、ウェブハーベスティング)。

必要なスキル
- C#またはVB.NETなどのMicrosoftのプログラミング言語を使用する基本的なプログラミングの基礎
- Web技術(HTML、JavaScript、JQuery、CSSなど)の基本的な理解とその動作理解
- DOM、XPath、HTML、CSSセレクタの基本的な知識
ツール
- Microsoft Visual Studio 2010以上
- ChromeのウェブインスペクターやFirefoxのFirebugなど、ブラウザ用のウェブ開発者拡張機能
なぜスクレイピングを行うのか? (理由と概念)
次の能力を備えた製品やソリューションを構築したい場合:
- ウェブサイトデータ抽出
- 複数のウェブサイトからのコンテンツ、価格、機能の比較
- ウェブサイトコンテンツのスキャンとキャッシュ
上記の理由が1つ以上ある場合、IronWebScraperはニーズに合った優れたライブラリです
IronWebScraperのインストール方法
あなたがCreate a New Project(付録Aを参照)した後、IronWebScraperライブラリをプロジェクトに追加するには、NuGetを使用してライブラリを自動的に挿入するか、DLLを手動でインストールしてください。
NuGetを使用したインストール
NuGetを使用して私たちのプロジェクトにIronWebScraperライブラリを追加するには、ビジュアルインターフェイス(NuGetパッケージマネージャー)を使用するか、パッケージマネージャーコンソールを使用してコマンドで行います。
NuGetパッケージマネージャーを使用
- マウスを使用 -> プロジェクト名を右クリック -> NuGetパッケージの管理を選択
- ブラウズタブから ->
IronWebScraperを検索 -> インストール - Okをクリック
- 完了です
NuGetパッケージコンソールを使用
- ツールから -> NuGetパッケージマネージャー -> パッケージマネージャーコンソール
- クラスライブラリプロジェクトをデフォルトプロジェクトとして選択
- コマンドを実行 ->
Install-Package IronWebScraper
手動でインストール
-
https://ironsoftware.comに移動します
-
IronWebScraperをクリックするか、URL https://ironsoftware.com/csharp/webscraper/ を使用してそのページに直接移動します
-
DLLをダウンロード
-
ダウンロードした圧縮ファイルを解凍
-
Visual Studioでプロジェクトを右クリック -> 追加 -> 参照 -> ブラウズ

-
抽出されたフォルダに移動 ->
netstandard2.0-> そしてすべての.dllファイルを選択します
-
これで完了です!
HelloScraper - 最初のIronWebScraperサンプル
通常通り、Hello Scraperアプリの実装から始めて、IronWebScraperを使用する第一歩を踏み出しましょう。
- 「IronWebScraperSample」という名前の新しいコンソールアプリケーションを作成しました
IronWebScraperサンプルを作成する手順
-
フォルダを作成し、「HelloScraperSample」と名付けます
-
その後、新しいクラスを追加し、名前を
HelloScraperにします
-
このコードスニペットを
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); } } }Public Class HelloScraper Inherits 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 Overrides Sub Init() License.LicenseKey = "LicenseKey" ' Write License Key Me.LoggingLevel = WebScraper.LogLevel.All ' Log all events Me.Request("https://blog.scrapinghub.com", AddressOf Parse) ' Initialize a web request to the given URL End Sub ''' <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 Overrides Sub Parse(ByVal response As Response) ' Set working directory for the project Me.WorkingDirectory = AppSetting.GetAppRoot() & "\HelloScraperSample\Output\" ' Loop on all links For Each titleLink In response.Css("h2.entry-title a") ' Read link text Dim title As String = titleLink.TextContentClean ' Save result to file Scrape(New ScrapedData() From { { "Title", title } }, "HelloScraper.json") Next titleLink ' Loop on all links for pagination If response.CssExists("div.prev-post > a[href]") Then ' Get next page URL Dim nextPage = response.Css("div.prev-post > a[href]")(0).Attributes("href") ' Scrape next URL Me.Request(nextPage, AddressOf Parse) End If End Sub End ClassPublic Class HelloScraper Inherits 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 Overrides Sub Init() License.LicenseKey = "LicenseKey" ' Write License Key Me.LoggingLevel = WebScraper.LogLevel.All ' Log all events Me.Request("https://blog.scrapinghub.com", AddressOf Parse) ' Initialize a web request to the given URL End Sub ''' <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 Overrides Sub Parse(ByVal response As Response) ' Set working directory for the project Me.WorkingDirectory = AppSetting.GetAppRoot() & "\HelloScraperSample\Output\" ' Loop on all links For Each titleLink In response.Css("h2.entry-title a") ' Read link text Dim title As String = titleLink.TextContentClean ' Save result to file Scrape(New ScrapedData() From { { "Title", title } }, "HelloScraper.json") Next titleLink ' Loop on all links for pagination If response.CssExists("div.prev-post > a[href]") Then ' Get next page URL Dim nextPage = response.Css("div.prev-post > a[href]")(0).Attributes("href") ' Scrape next URL Me.Request(nextPage, AddressOf Parse) End If End Sub End Class -
今、スクレープを開始するために、このコードスニペットを
Mainに追加しますstatic void Main(string[] args) { // Create Object From Hello Scrape class HelloScraperSample.HelloScraper scrape = new HelloScraperSample.HelloScraper(); // Start Scraping scrape.Start(); }static void Main(string[] args) { // Create Object From Hello Scrape class HelloScraperSample.HelloScraper scrape = new HelloScraperSample.HelloScraper(); // Start Scraping scrape.Start(); }Shared Sub Main(ByVal args() As String) ' Create Object From Hello Scrape class Dim scrape As New HelloScraperSample.HelloScraper() ' Start Scraping scrape.Start() End SubShared Sub Main(ByVal args() As String) ' Create Object From Hello Scrape class Dim scrape As New HelloScraperSample.HelloScraper() ' Start Scraping scrape.Start() End Sub -
結果は
WebScraper.WorkingDirectory/classname.Json形式でファイルに保存されます
コード概要
Scrape.Start()は以下のようにスクレイピングロジックをトリガーします:
Init()メソッドを呼び出して、変数の初期化、プロパティのスクレープ、および動作属性を行います。Init()でRequest("https://blog.scrapinghub.com", Parse)を用いて開始ページのリクエストを設定します。- 複数のHTTPリクエストとスレッドを並行して処理しながら、コードを同期的に保ち、デバッグしやすくします。
Init()の後にParse()メソッドがトリガーされ、レスポンスを処理し、CSSセレクタを使用してデータを抽出し、JSON形式で保存します。
IronWebScraperライブラリの機能とオプション
更新されたドキュメントは手動インストール方法でダウンロードされたzipファイル内にあります(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();
}
}
}namespace IronWebScraperEngine
{
public class NewsScraper : IronWebScraper.WebScraper
{
public override void Init()
{
throw new NotImplementedException();
}
public override void Parse(Response response)
{
throw new NotImplementedException();
}
}
}Namespace IronWebScraperEngine
Public Class NewsScraper
Inherits IronWebScraper.WebScraper
Public Overrides Sub Init()
Throw New NotImplementedException()
End Sub
Public Overrides Sub Parse(ByVal response As Response)
Throw New NotImplementedException()
End Sub
End Class
End NamespaceNamespace IronWebScraperEngine
Public Class NewsScraper
Inherits IronWebScraper.WebScraper
Public Overrides Sub Init()
Throw New NotImplementedException()
End Sub
Public Overrides Sub Parse(ByVal response As Response)
Throw New NotImplementedException()
End Sub
End Class
End Namespace| プロパティ \ 関数 | タイプ | 説明 |
|---|---|---|
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) | メソッド | ウェブリクエストのキャッシュを有効にします。 |
MaxHttpConnectionLimit | Int | 許可されるオープンHTTPリクエスト(スレッド)の合計数を設定します。 |
RateLimitPerHost | TimeSpan | 指定されたドメインまたはIPアドレスへのリクエストの間の遅延(ポーズ)の最小礼儀定義を設定します。 |
OpenConnectionLimitPerHost | Int | 指定されたホスト名またはIPアドレスごとの同時HTTPリクエスト(スレッド)の許可数を設定します。 |
WorkingDirectory | string | データを保存する作業ディレクトリパスを設定します。 |
実世界のサンプルと実践
オンラインムービーサイトのスクレイピング
ムービーサイトをスクレイピングする例を作ってみましょう。
新しいクラスを追加し、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>
ムービー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 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 MovieScraper
Inherits WebScraper
Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
Me.Request("www.website.com", AddressOf Parse)
End Sub
Public Overrides Sub Parse(ByVal response As Response)
For Each div In response.Css("#movie-featured > div")
If div.GetAttribute("class") <> "clearfix" Then
Dim movieId = div.GetAttribute("data-movie-id")
Dim link = div.Css("a")(0)
Dim movieTitle = link.TextContentClean
Scrape(New ScrapedData() From {
{ "MovieId", movieId },
{ "MovieTitle", movieTitle }
},
"Movie.Jsonl")
End If
Next div
End Sub
End ClassPublic Class MovieScraper
Inherits WebScraper
Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
Me.Request("www.website.com", AddressOf Parse)
End Sub
Public Overrides Sub Parse(ByVal response As Response)
For Each div In response.Css("#movie-featured > div")
If div.GetAttribute("class") <> "clearfix" Then
Dim movieId = div.GetAttribute("data-movie-id")
Dim link = div.Css("a")(0)
Dim movieTitle = link.TextContentClean
Scrape(New ScrapedData() From {
{ "MovieId", movieId },
{ "MovieTitle", movieTitle }
},
"Movie.Jsonl")
End If
Next div
End Sub
End 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 ClassPublic Class Movie
Public Property Id As Integer
Public Property Title As String
Public Property URL As String
End Class今、私たちのコードを更新して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");
}
}
}
}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");
}
}
}
}Public Class MovieScraper
Inherits WebScraper
Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
Me.Request("https://website.com/", AddressOf Parse)
End Sub
Public Overrides Sub Parse(ByVal response As Response)
For Each div In response.Css("#movie-featured > div")
If div.GetAttribute("class") <> "clearfix" Then
Dim movie As New Movie With {
.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")
End If
Next div
End Sub
End ClassPublic Class MovieScraper
Inherits WebScraper
Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
Me.Request("https://website.com/", AddressOf Parse)
End Sub
Public Overrides Sub Parse(ByVal response As Response)
For Each div In response.Css("#movie-featured > div")
If div.GetAttribute("class") <> "clearfix" Then
Dim movie As New Movie With {
.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")
End If
Next div
End Sub
End Class詳細ページのスクレイピング
私たちの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; }
}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; }
}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 ClassPublic 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の機能を使用して、詳細ページに移動してスクレイピングします:
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");
}
}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");
}
}Public Class MovieScraper
Inherits WebScraper
Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
Me.Request("https://domain/", AddressOf Parse)
End Sub
Public Overrides Sub Parse(ByVal response As Response)
For Each div In response.Css("#movie-featured > div")
If div.GetAttribute("class") <> "clearfix" Then
Dim movie As New Movie With {
.Id = Convert.ToInt32(div.GetAttribute("data-movie-id")),
.Title = div.Css("a")(0).TextContentClean,
.URL = div.Css("a")(0).Attributes("href")
}
Me.Request(movie.URL, AddressOf ParseDetails, New MetaData() From {
{ "movie", movie }
})
End If
Next div
End Sub
Public Sub ParseDetails(ByVal response As Response)
Dim movie = response.MetaData.Get(Of Movie)("movie")
Dim div = response.Css("div.mvic-desc")(0)
movie.Description = div.Css("div.desc")(0).TextContentClean
movie.Genre = div.Css("div > p > a").Select(Function(element) element.TextContentClean).ToList()
movie.Actor = div.Css("div > p:nth-child(2) > a").Select(Function(element) element.TextContentClean).ToList()
Scrape(movie, "Movie.Jsonl")
End Sub
End ClassPublic Class MovieScraper
Inherits WebScraper
Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\MovieSample\Output\"
Me.Request("https://domain/", AddressOf Parse)
End Sub
Public Overrides Sub Parse(ByVal response As Response)
For Each div In response.Css("#movie-featured > div")
If div.GetAttribute("class") <> "clearfix" Then
Dim movie As New Movie With {
.Id = Convert.ToInt32(div.GetAttribute("data-movie-id")),
.Title = div.Css("a")(0).TextContentClean,
.URL = div.Css("a")(0).Attributes("href")
}
Me.Request(movie.URL, AddressOf ParseDetails, New MetaData() From {
{ "movie", movie }
})
End If
Next div
End Sub
Public Sub ParseDetails(ByVal response As Response)
Dim movie = response.MetaData.Get(Of Movie)("movie")
Dim div = response.Css("div.mvic-desc")(0)
movie.Description = div.Css("div.desc")(0).TextContentClean
movie.Genre = div.Css("div > p > a").Select(Function(element) element.TextContentClean).ToList()
movie.Actor = div.Css("div > p:nth-child(2) > a").Select(Function(element) element.TextContentClean).ToList()
Scrape(movie, "Movie.Jsonl")
End Sub
End ClassIronWebScraperライブラリの特徴
HttpIdentity機能
一部のシステムはコンテンツを閲覧するためにユーザーのログインを要求します; 資格情報にはHttpIdentityを使用してください。
HttpIdentity id = new HttpIdentity
{
NetworkUsername = "username",
NetworkPassword = "pwd"
};
Identities.Add(id);HttpIdentity id = new HttpIdentity
{
NetworkUsername = "username",
NetworkPassword = "pwd"
};
Identities.Add(id);Dim id As New HttpIdentity With {
.NetworkUsername = "username",
.NetworkPassword = "pwd"
}
Identities.Add(id)Dim id As New HttpIdentity With {
.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\";
EnableWebCache();
this.Request("http://www.WebSite.com", Parse);
}Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
EnableWebCache()
Me.Request("http://www.WebSite.com", Parse)
End SubPublic Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
EnableWebCache()
Me.Request("http://www.WebSite.com", Parse)
End Subスロットリング
接続数および速度を制御します:
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);
}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);
}Public Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
Me.MaxHttpConnectionLimit = 80
Me.RateLimitPerHost = TimeSpan.FromMilliseconds(50)
Me.OpenConnectionLimitPerHost = 25
Me.ObeyRobotsDotTxt = False
Me.ThrottleMode = Throttle.ByDomainHostName
Me.Request("https://www.Website.com", Parse)
End SubPublic Overrides Sub Init()
License.LicenseKey = "LicenseKey"
Me.LoggingLevel = WebScraper.LogLevel.All
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
Me.MaxHttpConnectionLimit = 80
Me.RateLimitPerHost = TimeSpan.FromMilliseconds(50)
Me.OpenConnectionLimitPerHost = 25
Me.ObeyRobotsDotTxt = False
Me.ThrottleMode = Throttle.ByDomainHostName
Me.Request("https://www.Website.com", Parse)
End Subスロットリングプロパティ
MaxHttpConnectionLimit
許可される開かれたHTTPリクエスト(スレッド)の合計数RateLimitPerHost
指定されたドメインまたはIPアドレスへのリクエスト間の最小礼儀遅延時間(ポーズ)OpenConnectionLimitPerHost
ホスト名またはIPアドレスごとの同時に許可されるHTTPリクエスト(スレッド)の数ThrottleMode
WebScraperがホスト名だけでなくホストサーバーのIPアドレスでも要求をインテリジェントに調整します。 これにより、一つのマシンにホストされている複数のスクレイピングしたドメインに対して礼儀正しくなります。
付録
Windowsフォームアプリケーションを作成する方法?
Visual Studio 2013以上を使用します。
- Visual Studioを開きます。
- ファイル -> 新規 -> プロジェクト

- Visual C#またはVB -> Windows -> Windowsフォームアプリケーションを選択。

プロジェクト名: IronScraperSample
場所: ディスク上の場所を選択してください。
ASP.NET Webフォームアプリケーションを作成する方法?
- Visual Studioを開きます。

- ファイル -> 新規 -> プロジェクト

- Visual C#またはVB -> Web -> ASP.NET Webアプリケーション(.NET Framework)を選択。

プロジェクト名: IronScraperSample
場所: ディスク上の場所を選択してください。
- ASP.NETテンプレートから、空のテンプレートを選択しWebフォームをチェックします。

- 基本的なASP.NET Webフォームプロジェクトが作成されます。

完全なチュートリアルのサンプル プロジェクト コードをここからダウンロード。
よくある質問
IronWebScraper とは何ですか?
IronWebScraperは、Webスクレイピング、データ抽出、Webコンテンツ解析用に設計された.NETライブラリで、Microsoft Visual Studioプロジェクトに統合することができます。
C# Webスクレイピングチュートリアルの対象者は誰ですか?
このチュートリアルは、基本的または高度なプログラミングスキルを持ち、高度なWebスクレイピング、データ収集、コンテンツ解析のソリューションを実装したいソフトウェア開発者を対象としています。
C#のWebスクレイピングチュートリアルを利用するために必要なスキルは何ですか?
C#またはVB.NETを使用したプログラミングの基本知識、HTML、JavaScript、JQuery、CSSなどのWeb技術の理解、およびDOM、XPath、HTML、およびCSSセレクターに慣れていることが必要です。
NuGetを使用してIronWebScraperをインストールするにはどうすればいいですか?
NuGetを通じてIronWebScraperをインストールするには、Visual StudioのNuGetパッケージマネージャーで「IronWebScraper」と検索し、インストールオプションをクリックしてください。
チュートリアルの中の「HelloScraper」アプリケーションの目的は何ですか?
「HelloScraper」アプリケーションは、IronWebScraperの基本的な実装を学ぶためのイントロダクトリ例として役立ち、JSON形式でデータを抽出し保存することを紹介します。
IronWebScraperは複数のWebリクエストを処理できますか?その方法は?
はい、IronWebScraperは複数のHTTPリクエストとスレッドを並列で処理することができ、デバッグが容易な同期コードを可能にします。
IronWebScraperはHTTPアイデンティティを処理するためにどのような機能を提供していますか?
IronWebScraperは、ユーザーがネットワーク認証情報を指定できるHttpIdentity機能を提供し、認証が必要なウェブサイトでのスクレイピングを可能にします。
IronWebScraperはサーバー負荷に配慮して、どのように丁寧なWebスクレイピングを保証するのですか?
IronWebScraperは、MaxHttpConnectionLimit、RateLimitPerHost、OpenConnectionLimitPerHostといったスロットリング機能を使用してリクエストの速度と数を管理し、丁寧で敬意のあるスクレイピングを保証します。
IronWebScraperを使用した開発に推奨されるツールは何ですか?
Microsoft Visual Studio 2010以上、およびChromeのウェブインスペクタやFirefoxのFirebugなどのブラウザ用のWeb開発者拡張機能が開発に推奨されます。
開発者は特定のデータ抽出ニーズに対してIronWebScraperの機能をどのように拡張できますか?
開発者はIronWebScraper.WebScraperクラスから継承して機能を拡張し、Init()やParse(Response response)のようなメソッドをオーバーライドすることで、カスタムデータ抽出ロジックを実装できます。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。