C#でブログをスクレイピングする方法
Iron WebScraperを使用して、C#またはVB.NETでブログのコンテンツを抽出しましょう。
このチュートリアルでは、WordPressブログ(または類似のもの)が.NETを使用してコンテンツに戻す方法を示します。
// Define a class that extends WebScraper from IronWebScraper
public class BlogScraper : WebScraper
{
/// <summary>
/// Override this method to initialize your web-scraper.
/// Set at least one start URL and configure domain or URL patterns.
/// </summary>
public override void Init()
{
// Set your license key for IronWebScraper
License.LicenseKey = "YourLicenseKey";
// Enable logging for all actions
this.LoggingLevel = WebScraper.LogLevel.All;
// Set a directory to store output and cache files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\BlogSample\Output\";
// Enable caching with a specific duration
EnableWebCache(new TimeSpan(1, 30, 30));
// Request the start URL and specify the response handler
this.Request("http://blogSite.com/", Parse);
}
}' Define a class that extends WebScraper from IronWebScraper
Public Class BlogScraper
Inherits WebScraper
''' <summary>
''' Override this method to initialize your web-scraper.
''' Set at least one start URL and configure domain or URL patterns.
''' </summary>
Public Overrides Sub Init()
' Set your license key for IronWebScraper
License.LicenseKey = "YourLicenseKey"
' Enable logging for all actions
Me.LoggingLevel = WebScraper.LogLevel.All
' Set a directory to store output and cache files
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\BlogSample\Output\"
' Enable caching with a specific duration
EnableWebCache(New TimeSpan(1, 30, 30))
' Request the start URL and specify the response handler
Me.Request("http://blogSite.com/", AddressOf Parse)
End Sub
End Class' Define a class that extends WebScraper from IronWebScraper
Public Class BlogScraper
Inherits WebScraper
''' <summary>
''' Override this method to initialize your web-scraper.
''' Set at least one start URL and configure domain or URL patterns.
''' </summary>
Public Overrides Sub Init()
' Set your license key for IronWebScraper
License.LicenseKey = "YourLicenseKey"
' Enable logging for all actions
Me.LoggingLevel = WebScraper.LogLevel.All
' Set a directory to store output and cache files
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\BlogSample\Output\"
' Enable caching with a specific duration
EnableWebCache(New TimeSpan(1, 30, 30))
' Request the start URL and specify the response handler
Me.Request("http://blogSite.com/", AddressOf Parse)
End Sub
End Class通常どおり、Scraper を作成し、WebScraper クラスから継承します。 この場合、それは「BlogScraper」です。
出力ディレクトリとして「\BlogSample\Output\」を設定し、すべての出力とキャッシュファイルを保存します。
次に、Webキャッシュを有効にして、要求されたページをキャッシュフォルダー「WebCache」に保存します。
次にParse関数を書きましょう。
/// <summary>
/// Override this method to handle the Http Response for your web scraper.
/// Add additional methods if you handle multiple page types.
/// </summary>
/// <param name="response">The HTTP Response object to parse.</param>
public override void Parse(Response response)
{
// Iterate over each link found in the section navigation
foreach (var link in response.Css("div.section-nav > ul > li > a"))
{
switch(link.TextContentClean)
{
case "Reviews":
{
// Handle reviews case
}
break;
case "Science":
{
// Handle science case
}
break;
default:
{
// Save the link title to a file
Scrape(new ScrapedData() { { "Title", link.TextContentClean } }, "BlogScraper.Jsonl");
}
break;
}
}
}/// <summary>
/// Override this method to handle the Http Response for your web scraper.
/// Add additional methods if you handle multiple page types.
/// </summary>
/// <param name="response">The HTTP Response object to parse.</param>
public override void Parse(Response response)
{
// Iterate over each link found in the section navigation
foreach (var link in response.Css("div.section-nav > ul > li > a"))
{
switch(link.TextContentClean)
{
case "Reviews":
{
// Handle reviews case
}
break;
case "Science":
{
// Handle science case
}
break;
default:
{
// Save the link title to a file
Scrape(new ScrapedData() { { "Title", link.TextContentClean } }, "BlogScraper.Jsonl");
}
break;
}
}
}''' <summary>
''' Override this method to handle the Http Response for your web scraper.
''' Add additional methods if you handle multiple page types.
''' </summary>
''' <param name="response">The HTTP Response object to parse.</param>
Public Overrides Sub Parse(ByVal response As Response)
' Iterate over each link found in the section navigation
For Each link In response.Css("div.section-nav > ul > li > a")
Select Case link.TextContentClean
Case "Reviews"
' Handle reviews case
Case "Science"
' Handle science case
Case Else
' Save the link title to a file
Scrape(New ScrapedData() From {
{ "Title", link.TextContentClean }
},
"BlogScraper.Jsonl")
End Select
Next link
End Sub''' <summary>
''' Override this method to handle the Http Response for your web scraper.
''' Add additional methods if you handle multiple page types.
''' </summary>
''' <param name="response">The HTTP Response object to parse.</param>
Public Overrides Sub Parse(ByVal response As Response)
' Iterate over each link found in the section navigation
For Each link In response.Css("div.section-nav > ul > li > a")
Select Case link.TextContentClean
Case "Reviews"
' Handle reviews case
Case "Science"
' Handle science case
Case Else
' Save the link title to a file
Scrape(New ScrapedData() From {
{ "Title", link.TextContentClean }
},
"BlogScraper.Jsonl")
End Select
Next link
End SubParse メソッド内で、トップメニューからカテゴリページ(映画、科学、レビューなど)へのすべてのリンクを取得します。
その後、リンクカテゴリに基づいて適切なパースメソッドに切り替えます。
Scienceページのためにオブジェクトモデルを準備しましょう:
/// <summary>
/// Represents a model for Science Page
/// </summary>
public class ScienceModel
{
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the author.
/// </summary>
public string Author { get; set; }
/// <summary>
/// Gets or sets the date.
/// </summary>
public string Date { get; set; }
/// <summary>
/// Gets or sets the image.
/// </summary>
public string Image { get; set; }
/// <summary>
/// Gets or sets the text.
/// </summary>
public string Text { get; set; }
}/// <summary>
/// Represents a model for Science Page
/// </summary>
public class ScienceModel
{
/// <summary>
/// Gets or sets the title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// Gets or sets the author.
/// </summary>
public string Author { get; set; }
/// <summary>
/// Gets or sets the date.
/// </summary>
public string Date { get; set; }
/// <summary>
/// Gets or sets the image.
/// </summary>
public string Image { get; set; }
/// <summary>
/// Gets or sets the text.
/// </summary>
public string Text { get; set; }
}''' <summary>
''' Represents a model for Science Page
''' </summary>
Public Class ScienceModel
''' <summary>
''' Gets or sets the title.
''' </summary>
Public Property Title As String
''' <summary>
''' Gets or sets the author.
''' </summary>
Public Property Author As String
''' <summary>
''' Gets or sets the date.
''' </summary>
Public Property Date As String
''' <summary>
''' Gets or sets the image.
''' </summary>
Public Property Image As String
''' <summary>
''' Gets or sets the text.
''' </summary>
Public Property Text As String
End Class''' <summary>
''' Represents a model for Science Page
''' </summary>
Public Class ScienceModel
''' <summary>
''' Gets or sets the title.
''' </summary>
Public Property Title As String
''' <summary>
''' Gets or sets the author.
''' </summary>
Public Property Author As String
''' <summary>
''' Gets or sets the date.
''' </summary>
Public Property Date As String
''' <summary>
''' Gets or sets the image.
''' </summary>
Public Property Image As String
''' <summary>
''' Gets or sets the text.
''' </summary>
Public Property Text As String
End Class次に、単一ページのスクレイプを実装しましょう。
/// <summary>
/// Parses the reviews from the response.
/// </summary>
/// <param name="response">The HTTP Response object.</param>
public void ParseReviews(Response response)
{
// A list to hold Science models
var scienceList = new List<ScienceModel>();
foreach (var postBox in response.Css("section.main > div > div.post-list"))
{
var item = new ScienceModel
{
Title = postBox.Css("h1.headline > a")[0].TextContentClean,
Author = postBox.Css("div.author > a")[0].TextContentClean,
Date = postBox.Css("div.time > a")[0].TextContentClean,
Image = postBox.Css("div.image-wrapper.default-state > img")[0].Attributes["src"],
Text = postBox.Css("div.summary > p")[0].TextContentClean
};
scienceList.Add(item);
}
// Save the science list to a JSONL file
Scrape(scienceList, "BlogScience.Jsonl");
}/// <summary>
/// Parses the reviews from the response.
/// </summary>
/// <param name="response">The HTTP Response object.</param>
public void ParseReviews(Response response)
{
// A list to hold Science models
var scienceList = new List<ScienceModel>();
foreach (var postBox in response.Css("section.main > div > div.post-list"))
{
var item = new ScienceModel
{
Title = postBox.Css("h1.headline > a")[0].TextContentClean,
Author = postBox.Css("div.author > a")[0].TextContentClean,
Date = postBox.Css("div.time > a")[0].TextContentClean,
Image = postBox.Css("div.image-wrapper.default-state > img")[0].Attributes["src"],
Text = postBox.Css("div.summary > p")[0].TextContentClean
};
scienceList.Add(item);
}
// Save the science list to a JSONL file
Scrape(scienceList, "BlogScience.Jsonl");
}''' <summary>
''' Parses the reviews from the response.
''' </summary>
''' <param name="response">The HTTP Response object.</param>
Public Sub ParseReviews(ByVal response As Response)
' A list to hold Science models
Dim scienceList = New List(Of ScienceModel)()
For Each postBox In response.Css("section.main > div > div.post-list")
Dim item = New ScienceModel With {
.Title = postBox.Css("h1.headline > a")(0).TextContentClean,
.Author = postBox.Css("div.author > a")(0).TextContentClean,
.Date = postBox.Css("div.time > a")(0).TextContentClean,
.Image = postBox.Css("div.image-wrapper.default-state > img")(0).Attributes("src"),
.Text = postBox.Css("div.summary > p")(0).TextContentClean
}
scienceList.Add(item)
Next postBox
' Save the science list to a JSONL file
Scrape(scienceList, "BlogScience.Jsonl")
End Sub''' <summary>
''' Parses the reviews from the response.
''' </summary>
''' <param name="response">The HTTP Response object.</param>
Public Sub ParseReviews(ByVal response As Response)
' A list to hold Science models
Dim scienceList = New List(Of ScienceModel)()
For Each postBox In response.Css("section.main > div > div.post-list")
Dim item = New ScienceModel With {
.Title = postBox.Css("h1.headline > a")(0).TextContentClean,
.Author = postBox.Css("div.author > a")(0).TextContentClean,
.Date = postBox.Css("div.time > a")(0).TextContentClean,
.Image = postBox.Css("div.image-wrapper.default-state > img")(0).Attributes("src"),
.Text = postBox.Css("div.summary > p")(0).TextContentClean
}
scienceList.Add(item)
Next postBox
' Save the science list to a JSONL file
Scrape(scienceList, "BlogScience.Jsonl")
End Subモデルを作成した後で、Responseオブジェクトを解析し、その主な要素(タイトル、著者、日付、画像、テキスト)を深堀りできます。
次に、Scrape(object, fileName)を使用して、結果を別ファイルに保存します。
IronWebScraperの使用に関する完全なチュートリアルはこちらをクリックしてください
IronWebScraperで始めましょう

よくある質問
IronWebScraperは何に使われますか?
IronWebScraperは、C#またはVB.NET環境でのウェブスクレイピングタスクを容易にするように設計され、ウェブページからデータを抽出および処理するために使用されます。
IronWebScraperで開始URLを設定するにはどうすればよいですか?
IronWebScraperでは、Initメソッドをオーバーライドし、this.Request関数を使用して、スクレイピングしたいURLを指定することで、開始URLを設定できます。
IronWebScraperはキャッシュをどのように処理しますか?
IronWebScraperはキャッシュを有効にする機能を提供しており、EnableWebCacheメソッドを使用して、指定した期間ページをキャッシュディレクトリに保存することができます。
IronWebScraperでデータ抽出をカスタマイズできますか?
はい、IronWebScraperではParseメソッドをオーバーライドすることで、HTTPレスポンスおよびCSSセレクターに基づいて特定の情報を抽出できるようにカスタマイズできます。
IronWebScraperで解析された結果はどのように保存されますか?
IronWebScraperの解析結果はScrapeメソッドを使用して保存でき、データをJSONLなどのファイルに書き込むことで、抽出されたデータを構造的に保存することができます。
IronWebScraperはログをサポートしていますか?
はい、IronWebScraperはすべてのアクションのログ記録をサポートしており、Initメソッド内でLoggingLevelプロパティをWebScraper.LogLevel.Allに設定することで有効にできます。
スクレイピングされたデータの表現にはどのような構造が使われますか?
IronWebScraperでは、スクレイピングされたデータはScienceModelクラスのようなカスタムオブジェクトモデルで表され、タイトル、著者、日付、画像、テキストなどのプロパティを定義しています。
IronWebScraperで複数のページタイプをスクレイプすることは可能ですか?
はい、IronWebScraperを使用して、追加のメソッドを実装し、レスポンスハンドラを使って異なるカテゴリやセクションを処理することで、複数のページタイプをスクレイプすることができます。
IronWebScraperはどのように初期化されますか?
IronWebScraperはWebScraperを拡張するクラスを作成し、Initメソッドをオーバーライドすることで初期化されます。このセットアップでは、開始URL、ログ記録、キャッシュ、およびその他の必要なパラメータの設定を可能にします。
IronWebScraperにおけるサイエンスデータモデルの構造はどうなっていますか?
IronWebScraperの科学データモデルはScienceModelクラスを使用して構成されており、タイトル、著者、日付、画像、テキストのプロパティを含み、ブログ投稿コンテンツの簡単な抽出と操作を可能にします。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。
