Webscraping in C
IronWebScraperとは何ですか?
IronWebScraperは、C#および.NETプログラミングプラットフォーム用のクラスライブラリおよびフレームワークで、開発者がプログラムでウェブサイトを読み取り、そのコンテンツを抽出できるようにします。 これは、ウェブサイトや既存のイントラネットをリバースエンジニアリングして、データベースやJSONデータに変換するのに理想的です。 また、インターネットから大量のドキュメントをダウンロードするのにも便利です。
多くの点で、Iron Web ScraperはPythonのScrapyライブラリに似ていますが、C#の利点、特にウェブスクレイピングプロセス中にコードをステップ実行してデバッグできる能力を活用しています。
インストール
最初のステップは、Iron Web Scraperをインストールすることです。これは、NuGetからか、当社のウェブサイトからDLLをダウンロードすることで行えます。
必要なすべてのクラスは、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
特定のウェブサイトをスクレイプするには、そのウェブサイトを読み取るための独自のクラスを作成する必要があります。このクラスはWeb Scraperを拡張します。 このクラスに、Init などのいくつかのメソッドを追加します。これらのメソッドでは、初期設定を設定して最初のリクエストを開始できます。これにより、Web サイト全体がスクレイピングされる連鎖反応が発生します。
また、少なくとも 1 つの Parse メソッドを追加する必要があります。 Parseメソッドは、インターネットからダウンロードされたウェブページを読み取り、jQueryのようなCSSセレクタを使用してコンテンツを選択し、使用するための関連するテキストや画像を抽出します。
Parse メソッド内で、クローラーが引き続き追跡するハイパーリンクと無視するハイパーリンクを指定することもできます。
スクレイプメソッドを使用して、データを抽出し、便利なJSONスタイルのファイル形式にダンプして後で使用することができます。
今後のステップ
Iron Web Scraperの詳細については、APIリファレンスドキュメントをお読みになり、ドキュメントのチュートリアルセクション内のサンプルをご覧になることをお勧めします。
次におすすめする例はC# "blog" ウェブスクレイピング例で、WordPressブログなどのブログからテキストコンテンツを抽出する方法を学びます。 これは、サイト移行において非常に役立つかもしれません。
そこから、進んだウェブスクレイピングのチュートリアルの他の例を見ていくことができます。そこでは、多種多様なページを持つウェブサイト、eコマースサイト、インターネットからデータをスクレイプする際の複数のプロキシ、ID、ログインの使用方法などの概念を見ていくことができます。

