Webscraping in C#

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

IronWebScraperとは何ですか?

IronWebScraperは、C#および.NETプログラミングプラットフォーム用のクラスライブラリおよびフレームワークで、開発者がプログラムでウェブサイトを読み取り、そのコンテンツを抽出できるようにします。 これは、ウェブサイトや既存のイントラネットをリバースエンジニアリングして、データベースやJSONデータに変換するのに理想的です。 また、インターネットから大量のドキュメントをダウンロードするのにも便利です。

多くの点で、Iron Web ScraperはPythonのScrapyライブラリに似ていますが、C#の利点、特にウェブスクレイピングプロセス中にコードをステップ実行してデバッグできる能力を活用しています。

インストール

Your first step will be to install Iron Web Scraper, which you may do from NuGet or by downloading the DLL from our website.

必要なすべてのクラスは、Iron Web Scraperの名前空間内にあります。

Install-Package IronWebScraper

人気のある使用例

ウェブサイトをデータベースに移行する

IronWebScraperは、ウェブサイトを構造化データベースに再エンジニアリングするためのツールとメソッドを提供します。 この技術は、レガシーウェブサイトやイントラネットから新しいC#アプリケーションへコンテンツを移行する際に役立ちます。

ウェブサイトの移行

C#で部分的または完全なウェブサイトのコンテンツを簡単に抽出できることは、ウェブサイトやイントラネットリソースの移行またはアップグレードにおける時間とコストの影響を減少させます。 これは、直接的なSQL変換よりもはるかに効率的である可能性があります。なぜなら、それぞれのウェブページで見られるものにデータを平坦化し、以前のSQLデータ構造を理解する必要もなく、複雑なSQLクエリを作成する必要もないからです。

検索インデックスの充実

Iron Web Scraperは、組織内の検索エンジンが正確に充実するために、あなたのウェブサイトやイントラネットに向けて構造化データを読んで各ページを読み取り、正しいデータを抽出することができます。

IronWebScraperは、検索インデックスのスクレイプコンテンツに最適なツールです。 IronSearchのような検索アプリケーションは、IronWebScraperから構造化コンテンツを読み取り、強力なエンタープライズ検索システムを構築できます。

Iron Webscraperの使用法

Iron Web Scraperの使い方を学ぶには、例を参照するのが最善です。 この基本的な例は、ウェブサイトブログからタイトルをスクレイプするクラスを作成します。

using IronWebScraper;

namespace WebScrapingProject
{
    class MainClass
    {
        public static void Main(string [] args)
        {
            var scraper = new BlogScraper();
            scraper.Start();
        }
    }

    class BlogScraper : WebScraper
    {
        // Initialize scraper settings and make the first request
        public override void Init()
        {
            // Set logging level to show all log messages
            this.LoggingLevel = WebScraper.LogLevel.All;

            // Request the initial page to start scraping
            this.Request("https://ironpdf.com/blog/", Parse);
        }

        // Method to handle parsing of the page response
        public override void Parse(Response response)
        {
            // Loop through each blog post title link found by CSS selector
            foreach (var title_link in response.Css("h2.entry-title a"))
            {
                // Clean and extract the title text
                string strTitle = title_link.TextContentClean;

                // Store the extracted title for later use
                Scrape(new ScrapedData() { { "Title", strTitle } });
            }

            // Check if there is a link to the previous post page and if exists, follow it
            if (response.CssExists("div.prev-post > a[href]"))
            {
                // Get the URL for the next page
                var next_page = response.Css("div.prev-post > a[href]")[0].Attributes["href"];

                // Request the next page to continue scraping
                this.Request(next_page, Parse);
            }
        }
    }
}
using IronWebScraper;

namespace WebScrapingProject
{
    class MainClass
    {
        public static void Main(string [] args)
        {
            var scraper = new BlogScraper();
            scraper.Start();
        }
    }

    class BlogScraper : WebScraper
    {
        // Initialize scraper settings and make the first request
        public override void Init()
        {
            // Set logging level to show all log messages
            this.LoggingLevel = WebScraper.LogLevel.All;

            // Request the initial page to start scraping
            this.Request("https://ironpdf.com/blog/", Parse);
        }

        // Method to handle parsing of the page response
        public override void Parse(Response response)
        {
            // Loop through each blog post title link found by CSS selector
            foreach (var title_link in response.Css("h2.entry-title a"))
            {
                // Clean and extract the title text
                string strTitle = title_link.TextContentClean;

                // Store the extracted title for later use
                Scrape(new ScrapedData() { { "Title", strTitle } });
            }

            // Check if there is a link to the previous post page and if exists, follow it
            if (response.CssExists("div.prev-post > a[href]"))
            {
                // Get the URL for the next page
                var next_page = response.Css("div.prev-post > a[href]")[0].Attributes["href"];

                // Request the next page to continue scraping
                this.Request(next_page, Parse);
            }
        }
    }
}
Imports IronWebScraper

Namespace WebScrapingProject
	Friend Class MainClass
		Public Shared Sub Main(ByVal args() As String)
			Dim scraper = New BlogScraper()
			scraper.Start()
		End Sub
	End Class

	Friend Class BlogScraper
		Inherits WebScraper

		' Initialize scraper settings and make the first request
		Public Overrides Sub Init()
			' Set logging level to show all log messages
			Me.LoggingLevel = WebScraper.LogLevel.All

			' Request the initial page to start scraping
			Me.Request("https://ironpdf.com/blog/", AddressOf Parse)
		End Sub

		' Method to handle parsing of the page response
		Public Overrides Sub Parse(ByVal response As Response)
			' Loop through each blog post title link found by CSS selector
			For Each title_link In response.Css("h2.entry-title a")
				' Clean and extract the title text
				Dim strTitle As String = title_link.TextContentClean

				' Store the extracted title for later use
				Scrape(New ScrapedData() From {
					{ "Title", strTitle }
				})
			Next title_link

			' Check if there is a link to the previous post page and if exists, follow it
			If response.CssExists("div.prev-post > a[href]") Then
				' Get the URL for the next page
				Dim next_page = response.Css("div.prev-post > a[href]")(0).Attributes("href")

				' Request the next page to continue scraping
				Me.Request(next_page, AddressOf Parse)
			End If
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

特定のウェブサイトをスクレイプするには、そのウェブサイトを読み取るための独自のクラスを作成する必要があります。このクラスはWeb Scraperを拡張します。 私たちは、このクラスにいくつかのメソッドを追加し、その中に最初のリクエストを開始できるInitを含んで、全体のウェブサイトがスクレイプされる連鎖反応を引き起こします。

少なくとも1つのParseメソッドを追加する必要があります。 Parseメソッドは、インターネットからダウンロードされたウェブページを読み取り、jQueryのようなCSSセレクタを使用してコンテンツを選択し、使用するための関連するテキストや画像を抽出します。

Parseメソッド内で、クローラーが引き続きフォローするハイパーリンクと無視するハイパーリンクを指定することもできます。

スクレイプメソッドを使用して、データを抽出し、便利なJSONスタイルのファイル形式にダンプして後で使用することができます。

今後のステップ

Iron Web Scraperについてもっと学ぶためには、APIリファレンスドキュメントを読むことをお勧めし、その後、ドキュメントのチュートリアルセクション内の例を見ていくことを開始してください。

次にお勧めするのは、C#「ブログ」ウェブスクレイピングの例です。ここでは、WordPressブログのようなブログからテキストコンテンツを抽出する方法を学びます。 これは、サイト移行において非常に役立つかもしれません。

そこから、進んだウェブスクレイピングのチュートリアルの他の例を見ていくことができます。そこでは、多種多様なページを持つウェブサイト、eコマースサイト、インターネットからデータをスクレイプする際の複数のプロキシ、ID、ログインの使用方法などの概念を見ていくことができます。

Curtis Chau
テクニカルライター

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

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

準備はいいですか?
Nuget ダウンロード 122,916 | バージョン: 2025.11 ただ今リリースされました