Webscraping in C

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWebScraper란 무엇인가요?

IronWebScraper는 C# 및 .NET 프로그래밍 플랫폼용 클래스 라이브러리 및 프레임워크로, 개발자가 웹사이트를 프로그래밍 방식으로 읽고 콘텐츠를 추출할 수 있도록 해줍니다. 이는 웹사이트나 기존 인트라넷을 역설계하여 데이터베이스 또는 JSON 데이터로 변환하는 데 이상적입니다. 인터넷에서 대용량 문서를 다운로드할 때도 유용합니다.

여러 측면에서 IronWebScraper는 Python의 Scrapy 라이브러리와 유사하지만, C#의 장점, 특히 웹 스크래핑 프로세스가 진행 중이고 디버그할 수 있는 코드를 단계별로 실행하는 능력을 활용합니다.

설치

IronWebScraper를 설치하는 첫 번째 단계로, NuGet에서 다운로드하거나 우리 웹사이트에서 DLL을 다운로드하여 설치할 수 있습니다.

필요한 모든 클래스는 IronWebScraper 네임스페이스에서 찾을 수 있습니다.

Install-Package IronWebScraper

일반적인 사용 사례

웹사이트를 데이터베이스로 마이그레이션하기

IronWebScraper는 웹사이트를 구조화된 데이터베이스로 재구성할 수 있는 도구와 방법을 제공합니다. 이 기술은 기존 웹사이트 및 인트라넷의 콘텐츠를 새로운 C# 애플리케이션으로 마이그레이션할 때 유용합니다.

웹사이트 이전

C#을 사용하여 웹사이트의 일부 또는 전체 콘텐츠를 쉽게 추출할 수 있으므로 웹사이트 및 인트라넷 리소스를 마이그레이션하거나 업그레이드하는 데 소요되는 시간과 비용을 줄일 수 있습니다. 이 방법은 데이터를 각 웹페이지에 표시될 수 있는 형태로 단순화하기 때문에 직접적인 SQL 변환보다 훨씬 효율적일 수 있으며, 이전 SQL 데이터 구조를 이해하거나 복잡한 SQL 쿼리를 작성할 필요가 없습니다.

검색 인덱스 채우기

IronWebScraper를 사용하는 경우, 구조화된 데이터를 읽거나, 모든 페이지를 읽고, 조직 내 검색 엔진에 정밀하게 데이터를 입력할 수 있도록 정확히 데이터를 추출하기 위해 자신의 웹사이트나 인트라넷에 철저히 집중할 수 있습니다.

IronWebScraper는 검색 엔진 색인용 콘텐츠를 스크래핑하는 데 이상적인 도구입니다. IronSearch와 같은 검색 애플리케이션은 IronWebScraper에서 구조화된 콘텐츠를 읽어 강력한 기업용 검색 시스템을 구축할 수 있습니다.

IronWebScraper 사용

IronWebScraper 사용 방법을 배우려면 예제를 살펴보는 것이 최선입니다. 이 기본적인 예제는 웹사이트 블로그에서 제목을 추출하는 클래스를 생성합니다.

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
$vbLabelText   $csharpLabel

특정 웹사이트의 데이터를 추출하려면 해당 웹사이트를 읽는 클래스를 직접 만들어야 합니다. 이 클래스는 Web Scraper 클래스를 상속받습니다. 이 클래스에 몇 가지 메서드를 추가할 것입니다. 초기 설정을 설정하고 첫 요청을 시작할 수 있는 Init를 포함하여, 이 요청은 결국 체인 반응을 일으켜 전체 웹사이트가 스크랩될 것입니다.

우리는 최소한 하나의 Parse 메서드를 추가해야 합니다. 파싱 ​​메서드는 인터넷에서 다운로드한 웹페이지를 읽고 jQuery와 유사한 CSS 선택자를 사용하여 콘텐츠를 선택하고 관련 텍스트 및/또는 이미지를 추출하여 사용합니다.

Parse 메서드 내에서 크롤러가 계속 따라가기를 원하는 하이퍼링크와 무시할 하이퍼링크를 지정할 수도 있습니다.

우리는 Scrape 메서드를 사용하여 데이터를 추출하고 나중에 사용하기 편리한 JSON 스타일 파일 형식으로 저장할 수 있습니다.

앞으로 나아가기

IronWebScraper에 대해 더 알아보려면 API 참조 문서를 읽어보신 후, 문서의 튜토리얼 섹션에 있는 예제를 살펴보시기 바랍니다.

다음으로 살펴볼 예제는 C# "블로그" 웹 스크래핑 예제 입니다. 이 예제를 통해 워드프레스 블로그와 같은 블로그에서 텍스트 콘텐츠를 추출하는 방법을 알아볼 수 있습니다. 이는 사이트 이전 시 매우 유용할 수 있습니다.

여기서 더 나아가 다양한 유형의 페이지로 구성된 웹사이트, 전자상거래 웹사이트, 그리고 인터넷에서 데이터를 스크래핑할 때 여러 프록시, ID 및 로그인을 사용하는 방법과 같은 개념을 살펴보는 다른 고급 웹 스크래핑 튜토리얼 예제를 살펴볼 수 있습니다.

Darrius Serrant
풀스택 소프트웨어 엔지니어 (웹 운영)

다리우스 세런트는 마이애미 대학교에서 컴퓨터 과학 학사 학위를 받았으며, Iron Software에서 풀 스택 웹 운영 마케팅 엔지니어로 근무하고 있습니다. 어린 시절부터 코딩에 매료되었던 그는 컴퓨팅이 신비로우면서도 접근하기 쉬운 분야라고 생각했고, 창의력과 문제 해결 능력을 발휘하기에 완벽한 매체라고 여겼습니다.

Iron Software에서 다리우스는 새로운 것을 만들고 복잡한 개념을 단순화하여 더 쉽게 이해할 수 있도록 하는 것을 즐깁니다. 그는 사내 개발자로서 학생들을 가르치는 데에도 자원하여 차세대 인재들과 전문 지식을 공유하고 있습니다.

다리우스에게 있어 그의 일은 가치 있고 실질적인 영향을 미치기 때문에 보람 있는 일입니다.

시작할 준비 되셨나요?
Nuget 다운로드 140,761 | 버전: 2026.7 방금 출시
Still Scrolling Icon

아직도 스크롤하고 계신가요?

빠른 증거를 원하시나요? PM > Install-Package IronWebScraper
샘플 실행 대상 사이트가 구조화된 데이터로 변환됩니다.