How to Scrape Data from Websites in C

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

IronWebscraperは、ウェブスクレイピング、ウェブデータ抽出、およびウェブコンテンツの解析を行うため for .NETライブラリです。 これは、Microsoft Visual Studio プロジェクトに追加して、開発および本番環境で利用できる、使いやすいライブラリです。

IronWebScraperには、許可・禁止するページ、オブジェクト、メディアなどを制御する機能など、多くの独自の機能と能力があります。また、複数のIDの管理やWebキャッシュの管理も可能であり、このチュートリアルではこれらをはじめとする多くの機能について解説します。

IronWebscraper を始める

今日あなたのプロジェクトでIronWebScraperを無料トライアルで使用開始。

最初のステップ:
green arrow pointer


対象読者

このチュートリアルは、高度なスクレイピング機能(Webサイトのスクレイピング、Webサイトデータの収集・抽出、Webサイトコンテンツの解析、Webハーベスティング)のためのソリューションを構築・実装したいと考えている、基礎または高度なプログラミングスキルを持つソフトウェア開発者を対象としています。

Webスクレイピングの画像

必要なスキル

  1. C#やVB.NETなどのMicrosoftプログラミング言語のいずれかを使用したプログラミングの基礎知識
  2. Web技術(HTML、JavaScript、jQuery、CSSなど)およびその仕組みに関する基本的な理解
  3. DOM、XPath、HTML、およびCSSセレクタに関する基礎知識

ツール

  1. Microsoft Visual Studio 2010 以降
  2. Chrome用のWeb InspectorやFirefox用のFirebugなど、ブラウザ向けのWeb開発者向け拡張機能

なぜスクレイピングを行うのか? (Reasons and Concepts)

次のような機能を備えた製品やソリューションを構築したい場合:

  1. ウェブサイトのデータを抽出する
  2. 複数のウェブサイトから内容、価格、機能などを比較する
  3. ウェブサイトコンテンツのスキャンとキャッシュ

上記の理由のいずれかに当てはまる場合、IronWebScraperはお客様のニーズに最適なライブラリです

IronWebscraperのインストール方法

IronWebScraperライブラリをプロジェクトに追加できます。

NuGet を使用してインストールしてください

NuGet を使用してプロジェクトに IronWebScraper ライブラリを追加するには、ビジュアルインターフェース(NuGet パッケージマネージャー)を使用するか、パッケージマネージャーコンソールからコマンドを実行します。

NuGet パッケージ マネージャーの使用

  1. マウスを使用 -> プロジェクト名を右クリック -> [NuGet パッケージの管理] を選択
  2. [ブラウズ] タブから -> IronWebScraper を検索 -> インストール
  3. [OK] をクリックします
  4. これで完了です

NuGet パッケージ コンソールの使用

  1. [ツール] → [NuGet パッケージ マネージャー] → [パッケージ マネージャー コンソール]
  2. デフォルトのプロジェクトとして"クラス ライブラリ プロジェクト"を選択する
  3. コマンドを実行 -> Install-Package IronWebScraper

手動でインストールする

  1. 以下のページにアクセスしてください </https:>
  2. IronWebscraperをクリックするか、URLを使用してそのページに直接アクセスしてください https://ironsoftware.com/csharp/webscraper/
  3. [DLLのダウンロード]をクリックします。
  4. ダウンロードした圧縮ファイルを解凍する
  5. Visual Studioでプロジェクトを右クリック -> [追加] -> [参照] -> [参照]

    DLLを使用してIronWebscraperを追加する

  6. 抽出されたフォルダ -> netstandard2.0 -> に移動し、すべての .dll ファイルを選択してください

    DLL 2 を使用して IronWebscraper を追加する

  7. これで完了です!

HelloScraper - IronWebScraperの最初のサンプル

いつものように、まずは"Hello Scraper App"を実装し、IronWebScraperを使った最初のステップを踏み出します。

  • "IronWebScraperSample"という名前の新しいコンソールアプリケーションを作成しました

IronWebscraper サンプルを作成する手順

  1. フォルダを作成し、"HelloScraperSample"と名前を付けます
  2. 次に、新しいクラスを追加し、その名前を HelloScraper とします。 HelloScraper クラスの追加

  3. このコードスニペットを 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 : 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 Class
    $vbLabelText   $csharpLabel
  4. それでは、スクレイピングを開始するために、このコードスニペットを 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 Sub
    $vbLabelText   $csharpLabel
  5. 翻訳結果は、WebScraper.WorkingDirectory/classname.Jsonという形式のファイルに保存されます。 HelloScraper の結果

コードの概要

Scrape.Start() は、次のようにスクレイピングロジックを起動します:

  1. Init() メソッドを呼び出し、変数の初期化、プロパティのスクレイピング、および動作属性の取得を行います。
  2. Init()Request("https://blog.scrapinghub.com", Parse) を使用して、開始ページのリクエストを設定します。
  3. 複数のHTTPリクエストとスレッドを並行して処理し、コードの同期性を保ち、デバッグを容易にします。
  4. Parse() メソッドは Init() の後に呼び出され、レスポンスを処理して CSS セレクタを使用してデータを抽出し、JSON 形式で保存します。

IronWebscraperライブラリの機能とオプション

https://ironsoftware.com/csharp/webscraper/object-reference/更新されたドキュメントは、手動インストール方法(IronWebScraper Documentation.chm File)でダウンロードしたZIPファイル内に含まれています。また、ライブラリの最新アップデートについては、オンラインドキュメント(.)でご確認いただけます。

プロジェクトで 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 Namespace
$vbLabelText   $csharpLabel
プロパティ \ 関数 タイプ 説明
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) 方法 Webリクエストのキャッシュを有効にします。
MaxHttpConnectionLimit Int 許可される開いているHTTPリクエスト(スレッド)の総数を設定します。
RateLimitPerHost TimeSpan 特定のドメインまたはIPアドレスへのリクエスト間の、最低限の礼儀的な遅延(休止時間)を設定します。
OpenConnectionLimitPerHost Int ホスト名またはIPアドレスごとに、許可される同時HTTPリクエスト(スレッド)の数を設定します。
WorkingDirectory string データを保存するための作業ディレクトリのパスを設定します。

実例と実践

オンライン映画サイトのスクレイピング

映画サイトのデータをスクレイピングする例を作成してみましょう。

新しいクラスを追加し、その名前を MovieScraper とします:

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>
<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、タイトル、および詳細ページへのリンクがあります。 それでは、このデータのスクレイピングを始めましょう:

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 Class
$vbLabelText   $csharpLabel

構造化されたMovieクラス

フォーマットされたデータを保持するために、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 Class
$vbLabelText   $csharpLabel

それでは、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 Class
$vbLabelText   $csharpLabel

詳細ページのスクレイピング

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 Class
$vbLabelText   $csharpLabel

次に、詳細ページに移動し、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 Class
$vbLabelText   $csharpLabel

IronWebscraperライブラリの機能

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)
$vbLabelText   $csharpLabel

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 Sub
$vbLabelText   $csharpLabel

スロットリング

接続数と速度を制御する:

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 Sub
$vbLabelText   $csharpLabel

スロットリングのプロパティ

  • MaxHttpConnectionLimit
    許可されるオープンHTTPリクエスト(スレッド)の総数
  • RateLimitPerHost
    特定のドメインまたはIPアドレスへのリクエスト間の最小礼儀的な遅延(休止時間)
  • OpenConnectionLimitPerHost
    ホスト名またはIPアドレスごとの同時HTTPリクエスト(スレッド)の最大数
  • ThrottleMode
    WEBSCRAPERが、ホスト名だけでなくホストサーバーのIPアドレスによってもリクエストをインテリジェントにスロットリングするようにします。 これは、複数のスクレイピング対象ドメインが同一のサーバー上でホストされている場合に備えて、配慮した表現です。

付録

Windowsフォームアプリケーションの作成方法

Visual Studio 2013 以降を使用してください。

  1. Visual Studioを開きます。
  2. ファイル -> 新規作成 -> プロジェクト Enterprise 2015

  3. Visual C# または VB を選択し、[Windows]、[Windows Forms アプリケーション] の順に選択します。 Windows アプリの作成

プロジェクト名: IronScraperSample
場所: ディスク上の場所を選択してください。

ASP.NET Webフォームアプリケーションの作成方法

  1. Visual Studioを開きます。 Enterprise 2015

  2. ファイル -> 新規作成 -> プロジェクト 新規プロジェクト

  3. [Visual C#] または [VB] を選択し、[Web] → [ASP.NET Web Application (.NET Framework)] を選択します。 ASP .NET Webアプリケーション

プロジェクト名: IronScraperSample
場所: ディスク上の場所を選択してください。

  1. ASP.NET テンプレートから空のテンプレートを選択し、"Web Forms"にチェックを入れます。 ASP .NET テンプレート

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

チュートリアルのサンプルプロジェクトコードの完全版はこちらからダウンロードできます

よくある質問

C#でWebサイトからデータをスクレイピングする方法は?

IronWebScraperを使用して、C#でWebサイトからデータをスクレイピングできます。まずNuGet経由でライブラリをインストールし、基本的なコンソールアプリケーションを設定して、効率的にWebデータを抽出し始めましょう。

C#でウェブスクレイピングを行うための前提条件は何ですか?

C#でウェブスクレイピングを行うには、C#またはVB.NETの基本的なプログラミングスキルを持ち、HTML、JavaScript、CSSなどのWeb技術を理解し、DOM、XPath、CSSセレクターに精通している必要があります。

どのように.NETプロジェクトにウェブスクレイピングライブラリをインストールできますか?

IronWebScraperを.NETプロジェクトにインストールするには、NuGetパッケージマネージャーコンソールでInstall-Package IronWebScraperコマンドを使用するか、Visual StudioのNuGetパッケージマネージャーインターフェイスを通じてインストールしてください。

自分のウェブスクレイパーにリクエストスロットリングを実装するにはどうすればいいですか?

IronWebScraperを使用すると、サーバーへのリクエストの頻度を管理するためにリクエストスロットリングを実装することができます。MaxHttpConnectionLimitRateLimitPerHostOpenConnectionLimitPerHostなどの設定を使用して構成できます。

ウェブスクレイピングでウェブキャッシュを有効にする目的は何ですか?

ウェブスクレイピングでウェブキャッシュを有効にすると、以前の応答を保存して再利用することで、サーバーに送信されるリクエストの数を減少させるのに役立ちます。IronWebScraperではEnableWebCacheメソッドを使用して設定できます。

Webスクレイピングで認証を処理する方法は?

IronWebScraperを使用すると、HttpIdentityを使用して認証を管理し、ログインフォームや制限された領域の背後にあるコンテンツにアクセスできるようにし、保護されたリソースのスクレイピングを可能にします。

C#でのウェブスクレイパーの簡単な例は何ですか?

『HelloScraper』はチュートリアルで提供されるシンプルな例です。IronWebScraperを使用して基本的なウェブスクレイパーを設定し、リクエストを開始し、応答を解析する方法を示しています。

複雑なページ構造を処理するためにウェブスクレイパーをどのように拡張できますか?

IronWebScraperを使用すると、さまざまなページタイプを処理するためにParseメソッドをカスタマイズし、フレキシブルなデータ抽出戦略を可能にすることで、複雑なページ構造を処理するためにスクレイパーを拡張することができます。

ウェブスクレイピングライブラリを使用する利点は何ですか?

IronWebScraperのようなウェブスクレイピングライブラリを使用することで、データ抽出の効率化、ドメイン管理、リクエストスロットリング、キャッシュ、認証対応のサポートなどの利点があり、ウェブスクレイピングタスクの効率的な処理が可能になります。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 137,906 | バージョン: 2026.6 just released
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか? PM > Install-Package IronWebScraper
サンプルを実行する ターゲットサイトが構造化データになるのを見る。