Wie man einen Blog in C# scrapt
Lassen Sie uns Iron WebScraper verwenden, um Blog-Inhalte mit C# oder VB.NET zu extrahieren.
Diese Anleitung zeigt, wie ein WordPress-Blog (oder ein ähnlicher) mit .NET in Inhalte zurückgescrappt werden kann.
// 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 ClassWie üblich erstellen wir ein Scraper und erben von der WebScraper Klasse. In diesem Fall ist es "BlogScraper".
Wir legen ein Arbeitsverzeichnis auf "\BlogSample\Output" fest, in dem alle unsere Ausgabedateien und Cache-Dateien gespeichert werden können.
Dann aktivieren wir den Web-Cache, um angeforderte Seiten im Cache-Ordner "WebCache" zu speichern.
Jetzt schreiben wir eine Parse Funktion:
/// <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 SubInnerhalb der Parse Methode erhalten wir alle Links zu Kategorieseiten (Filme, Wissenschaft, Rezensionen usw.) aus dem oberen Menü.
Dann wechseln wir basierend auf der Link-Kategorie zu einer geeigneten Parse-Methode.
Bereiten wir unser Objektmodell für die Wissenschaftsseite vor:
/// <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 ClassJetzt implementieren wir ein einzelnes Page Scrape:
/// <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 SubNachdem wir unser Modell erstellt haben, können wir das Response Objekt parsen, um in seine Hauptelemente (Titel, Autor, Datum, Bild, Text) zu vertiefen.
Dann speichern wir unsere Ergebnisse in einer separaten Datei mit Scrape(object, fileName).
Klicken Sie hier für das vollständige Tutorial zur Verwendung von IronWebScraper
Fangen Sie mit IronWebScraper an

Häufig gestellte Fragen
Wofür wird IronWebScraper verwendet?
IronWebScraper wird verwendet, um Daten von Webseiten zu extrahieren und zu verarbeiten. Es ist speziell dafür ausgelegt, Web-Scraping-Aufgaben in C#- oder VB.NET-Umgebungen zu erleichtern.
Wie kann ich eine Start-URL in IronWebScraper festlegen?
In IronWebScraper können Sie eine Start-URL festlegen, indem Sie die Init-Methode überschreiben und die this.Request-Funktion verwenden, um die URL anzugeben, die Sie scrapen möchten.
Wie handhabt IronWebScraper das Caching?
IronWebScraper bietet eine Funktion zur Aktivierung des Cachings, die mit der EnableWebCache-Methode aktiviert werden kann. Dadurch können Sie angeforderte Seiten für eine bestimmte Dauer in einem Cache-Verzeichnis speichern.
Können Sie die Datenextraktion in IronWebScraper anpassen?
Ja, die Datenerfassung kann in IronWebScraper angepasst werden, indem die Parse-Methode überschrieben wird, sodass Sie spezifische Informationen basierend auf der HTTP-Antwort und CSS-Selektoren extrahieren können.
Wie werden die geparsten Ergebnisse in IronWebScraper gespeichert?
In IronWebScraper können geparste Ergebnisse mithilfe der Scrape-Methode gespeichert werden, die es ermöglicht, Daten in Dateien wie JSONL zu schreiben und somit eine strukturierte Speicherung der extrahierten Daten zu ermöglichen.
Unterstützt IronWebScraper Logging?
Ja, IronWebScraper unterstützt die Protokollierung aller Aktionen, die durch Setzen der LoggingLevel-Eigenschaft auf WebScraper.LogLevel.All innerhalb der Init-Methode aktiviert werden kann.
Welche Struktur wird zur Darstellung der gescrapeten Daten verwendet?
In IronWebScraper werden gescrapte Daten oft in einem benutzerdefinierten Objektmodell dargestellt, wie der ScienceModel-Klasse, die Eigenschaften wie Titel, Autor, Datum, Bild und Text definiert.
Ist es möglich, mehrere Seitentypen mit IronWebScraper zu scrape?
Ja, Sie können mehrere Seitentypen mit IronWebScraper scrapen, indem Sie zusätzliche Methoden implementieren und die Antworthandler verwenden, um verschiedene Kategorien oder Abschnitte zu verarbeiten.
Wie kann IronWebScraper initialisiert werden?
IronWebScraper wird initialisiert, indem eine Klasse erstellt wird, die WebScraper erweitert und die Init-Methode überschreibt. Diese Einrichtung ermöglicht die Konfiguration von Start-URLs, Protokollierung, Caching und anderen notwendigen Parametern.
Wie ist das Wissenschaftsdatenmodell in IronWebScraper strukturiert?
Das Wissenschaftsdatenmodell in IronWebScraper ist mithilfe der ScienceModel-Klasse strukturiert, die Eigenschaften für Titel, Autor, Datum, Bild und Text enthält und so eine einfache Extraktion und Manipulation von Blog-Beitragsinhalten ermöglicht.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.
