如何使用 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",所有的输出和缓存文件可以放在那里。
然后我们启用网络缓存,将请求的页面保存在缓存文件夹"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 Sub在Parse方法中,我们从顶层菜单获取到类别页面(电影、科学、评论等)的所有链接。
然后,我们根据链接类别切换到合适的解析方法。
让我们为科学页面准备我们的对象模型:
/// <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 用于从网页中提取和处理数据,专为在 C# 或 VB.NET 环境中便捷执行网络爬虫任务而设计。
如何在 IronWebScraper 中设置起始 URL?
在IronWebScraper中,您可以通过重写Init方法并使用this.Request函数来设置您希望抓取的起始URL。
IronWebScraper 如何处理缓存?
IronWebScraper提供了启用缓存的功能,可以使用EnableWebCache方法激活,该方法允许您将请求的页面保存到缓存目录中指定的时间。
您可以自定义 IronWebScraper 中的数据提取吗?
是的,可以通过重写Parse方法在IronWebScraper中自定义数据提取,允许您根据HTTP响应和CSS选择器提取特定信息。
解析结果如何在 IronWebScraper 中保存?
在IronWebScraper中,解析结果可以通过Scrape方法保存,该方法允许将数据写入JSONL等文件,从而以结构化方式存储提取的数据。
IronWebScraper 是否支持日志记录?
是的,IronWebScraper支持记录所有操作,可以通过在Init方法中将LoggingLevel属性设置为WebScraper.LogLevel.All来启用。
对于抓取的数据使用什么结构表示?
在IronWebScraper中,抓取的数据通常表示为自定义对象模型,例如ScienceModel类,该类定义了Title、Author、Date、Image和Text等属性。
是否可以使用 IronWebScraper 抓取多个页面类型?
可以,您可以通过实现附加方法并使用响应处理器来处理不同类别或章节,从而使用 IronWebScraper 抓取多个页面类型。
IronWebScraper 如何初始化?
通过创建一个扩展了WebScraper的类并重写Init方法来初始化IronWebScraper。这种设置允许配置起始URL、日志记录、缓存和其他必要参数。
IronWebScraper 中科学数据模型的结构如何?
IronWebScraper中的科学数据模型使用ScienceModel类结构化,它包括Title、Author、Date、Image和Text等属性,从而易于提取和操作博客文章内容。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。
