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에서 구조화된 콘텐츠를 읽어 강력한 기업용 검색 시스템을 구축할 수 있습니다.
IronWebScraper 사용
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이 포함됩니다. 이를 통해 초기 설정을 설정하고 첫 번째 요청을 시작할 수 있으며, 이는 전체 웹사이트가 스크랩되는 연쇄 반응을 일으킬 것입니다.
우리는 또한 적어도 하나의 Parse 메서드를 추가해야 합니다. 파싱 메서드는 인터넷에서 다운로드한 웹페이지를 읽고 jQuery와 유사한 CSS 선택자를 사용하여 콘텐츠를 선택하고 관련 텍스트 및/또는 이미지를 추출하여 사용합니다.
Parse 메서드 내에서 우리가 크롤러가 계속 추적할 하이퍼링크와 무시할 하이퍼링크를 지정할 수도 있습니다.
우리는 Scrape 메서드를 사용하여 데이터를 추출하고 나중에 사용하기 편리한 JSON 스타일 파일 형식으로 저장할 수 있습니다.
앞으로 나아가기
Iron Web Scraper에 대해 더 자세히 알아보려면 API 참조 문서를 읽어보신 후, 문서의 튜토리얼 섹션에 있는 예제를 살펴보시기 바랍니다.
다음으로 살펴볼 예제는 C# "블로그" 웹 스크래핑 예제 입니다. 이 예제를 통해 워드프레스 블로그와 같은 블로그에서 텍스트 콘텐츠를 추출하는 방법을 알아볼 수 있습니다. 이는 사이트 이전 시 매우 유용할 수 있습니다.
여기서 더 나아가 다양한 유형의 페이지로 구성된 웹사이트, 전자상거래 웹사이트, 그리고 인터넷에서 데이터를 스크래핑할 때 여러 프록시, ID 및 로그인을 사용하는 방법과 같은 개념을 살펴보는 다른 고급 웹 스크래핑 튜토리얼 예제를 살펴볼 수 있습니다.

