C#으로 블로그를 스크래핑하는 방법
Iron WebScraper를 사용하여 C# 또는 VB.NET으로 블로그 콘텐츠를 추출해 봅시다.
이 튜토리얼에서는 .NET 사용하여 WordPress 블로그(또는 유사한 웹사이트)에서 콘텐츠를 스크래핑하는 방법을 보여줍니다.
// 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는 무엇을 위해 사용되나요?
IronWebScraper는 웹 페이지에서 데이터를 추출하고 처리하기 위해 사용되며, 특히 C# 또는 VB.NET 환경에서 웹 스크래핑 작업을 용이하게 하기 위해 설계되었습니다.
IronWebScraper에서 시작 URL을 어떻게 설정할 수 있나요?
IronWebScraper에서 기본 URL을 설정하려면 Init 메서드를 오버라이드하고 this.Request 함수를 사용하여 크롤링할 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 클래스를 사용하여 구조화되며, 제목, 저자, 날짜, 이미지 및 텍스트 속성을 포함하여 블로그 게시물의 내용 추출 및 조작을 쉽게 할 수 있습니다.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.
