C# 고급 웹 스크래핑 기능: HTML 파싱 및 데이터 수집 심화
HttpIdentity 기능
일부 웹사이트 시스템은 콘텐츠를 보려면 사용자가 로그인해야 합니다. 이 경우, 우리는 HttpIdentity을(를) 사용할 수 있습니다. 설정 방법은 다음과 같습니다.
// Create a new instance of HttpIdentity
HttpIdentity id = new HttpIdentity();
// Set the network username and password for authentication
id.NetworkUsername = "username";
id.NetworkPassword = "pwd";
// Add the identity to the collection of identities
Identities.Add(id);
// Create a new instance of HttpIdentity
HttpIdentity id = new HttpIdentity();
// Set the network username and password for authentication
id.NetworkUsername = "username";
id.NetworkPassword = "pwd";
// Add the identity to the collection of identities
Identities.Add(id);
' Create a new instance of HttpIdentity
Dim id As New HttpIdentity()
' Set the network username and password for authentication
id.NetworkUsername = "username"
id.NetworkPassword = "pwd"
' Add the identity to the collection of identities
Identities.Add(id)
IronWebScraper의 가장 인상적이고 강력한 기능 중 하나는 수천 개의 고유한 사용자 자격 증명 및/또는 브라우저 엔진을 사용하여 여러 로그인 세션을 통해 웹사이트를 위장하거나 스크래핑할 수 있는 기능입니다.
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Define an array of proxies
var proxies = "IP-Proxy1:8080,IP-Proxy2:8081".Split(',');
// Iterate over common Chrome desktop user agents
foreach (var UA in IronWebScraper.CommonUserAgents.ChromeDesktopUserAgents)
{
// Iterate over the proxies
foreach (var proxy in proxies)
{
// Add a new HTTP identity with specific user agent and proxy
Identities.Add(new HttpIdentity()
{
UserAgent = UA,
UseCookies = true,
Proxy = proxy
});
}
}
// Make an initial request to the website with a parse method
this.Request("http://www.Website.com", Parse);
}
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Define an array of proxies
var proxies = "IP-Proxy1:8080,IP-Proxy2:8081".Split(',');
// Iterate over common Chrome desktop user agents
foreach (var UA in IronWebScraper.CommonUserAgents.ChromeDesktopUserAgents)
{
// Iterate over the proxies
foreach (var proxy in proxies)
{
// Add a new HTTP identity with specific user agent and proxy
Identities.Add(new HttpIdentity()
{
UserAgent = UA,
UseCookies = true,
Proxy = proxy
});
}
}
// Make an initial request to the website with a parse method
this.Request("http://www.Website.com", Parse);
}
Public Overrides Sub Init()
' Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey"
' Set the logging level to capture all logs
Me.LoggingLevel = WebScraper.LogLevel.All
' Assign the working directory for the output files
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
' Define an array of proxies
Dim proxies = "IP-Proxy1:8080,IP-Proxy2:8081".Split(","c)
' Iterate over common Chrome desktop user agents
For Each UA In IronWebScraper.CommonUserAgents.ChromeDesktopUserAgents
' Iterate over the proxies
For Each proxy In proxies
' Add a new HTTP identity with specific user agent and proxy
Identities.Add(New HttpIdentity() With {
.UserAgent = UA,
.UseCookies = True,
.Proxy = proxy
})
Next proxy
Next UA
' Make an initial request to the website with a parse method
Me.Request("http://www.Website.com", Parse)
End Sub
다양한 속성을 활용하여 각기 다른 동작을 구현할 수 있으므로 웹사이트에서 사용자를 차단하지 못하도록 할 수 있습니다.
이러한 속성 중 일부는 다음과 같습니다.
NetworkDomain: 사용자 인증에 사용될 네트워크 도메인입니다. Windows, NTLM, Kerberos, Linux, BSD 및 Mac OS X 네트워크를 지원합니다.NetworkUsername및NetworkPassword과 함께 사용해야 합니다.NetworkUsername: 사용자 인증에 사용될 네트워크/http 사용자 이름입니다. HTTP, Windows 네트워크, NTLM, Kerberos, Linux 네트워크, BSD 네트워크 및 Mac OS를 지원합니다.NetworkPassword: 사용자 인증에 사용될 네트워크/http 비밀번호입니다. HTTP, Windows 네트워크, NTLM, Kerberos, Linux 네트워크, BSD 네트워크 및 Mac OS를 지원합니다.Proxy: 프록시 설정을 설정합니다.UserAgent: 브라우저 엔진을 설정합니다 (예: Chrome 데스크톱, Chrome 모바일, Chrome 태블릿, IE, 및 Firefox 등).HttpRequestHeaders: 이 아이덴티티와 함께 사용할 사용자 정의 헤더 값을 위해,Dictionary<string, string>객체를 허용합니다.UseCookies: 쿠키 사용을 활성화/비활성화합니다.
IronWebScraper는 임의의 ID를 사용하여 스크래퍼를 실행합니다. 페이지를 파싱할 때 특정 식별자를 사용하도록 지정해야 하는 경우, 다음과 같이 할 수 있습니다.
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Create a new instance of HttpIdentity
HttpIdentity identity = new HttpIdentity();
// Set the network username and password for authentication
identity.NetworkUsername = "username";
identity.NetworkPassword = "pwd";
// Add the identity to the collection of identities
Identities.Add(identity);
// Make a request to the website with the specified identity
this.Request("http://www.Website.com", Parse, identity);
}
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Create a new instance of HttpIdentity
HttpIdentity identity = new HttpIdentity();
// Set the network username and password for authentication
identity.NetworkUsername = "username";
identity.NetworkPassword = "pwd";
// Add the identity to the collection of identities
Identities.Add(identity);
// Make a request to the website with the specified identity
this.Request("http://www.Website.com", Parse, identity);
}
Public Overrides Sub Init()
' Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey"
' Set the logging level to capture all logs
Me.LoggingLevel = WebScraper.LogLevel.All
' Assign the working directory for the output files
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
' Create a new instance of HttpIdentity
Dim identity As New HttpIdentity()
' Set the network username and password for authentication
identity.NetworkUsername = "username"
identity.NetworkPassword = "pwd"
' Add the identity to the collection of identities
Identities.Add(identity)
' Make a request to the website with the specified identity
Me.Request("http://www.Website.com", Parse, identity)
End Sub
웹 캐시 기능을 활성화하세요
이 기능은 요청된 페이지를 캐시하는 데 사용됩니다. 이는 개발 및 테스트 단계에서 자주 사용되며, 개발자가 코드 업데이트 후 재사용할 수 있도록 필요한 페이지를 캐시할 수 있게 해줍니다. 이를 통해 웹 스크래퍼를 다시 시작한 후에도 매번 실제 웹사이트에 연결할 필요 없이 캐시된 페이지에서 코드를 실행할 수 있습니다(액션 리플레이).
이를 Init() 메소드에서 사용할 수 있습니다:
// Enable web cache without an expiration time
EnableWebCache();
// OR enable web cache with a specified expiration time
EnableWebCache(new TimeSpan(1, 30, 30));
// Enable web cache without an expiration time
EnableWebCache();
// OR enable web cache with a specified expiration time
EnableWebCache(new TimeSpan(1, 30, 30));
' Enable web cache without an expiration time
EnableWebCache()
' OR enable web cache with a specified expiration time
EnableWebCache(New TimeSpan(1, 30, 30))
작업 디렉토리 폴더 아래의 WebCache 폴더에 캐시된 데이터를 저장합니다.
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Enable web cache with a specific expiration time of 1 hour, 30 minutes, and 30 seconds
EnableWebCache(new TimeSpan(1, 30, 30));
// Make an initial request to the website with a parse method
this.Request("http://www.Website.com", Parse);
}
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Enable web cache with a specific expiration time of 1 hour, 30 minutes, and 30 seconds
EnableWebCache(new TimeSpan(1, 30, 30));
// Make an initial request to the website with a parse method
this.Request("http://www.Website.com", Parse);
}
Public Overrides Sub Init()
' Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey"
' Set the logging level to capture all logs
Me.LoggingLevel = WebScraper.LogLevel.All
' Assign the working directory for the output files
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
' Enable web cache with a specific expiration time of 1 hour, 30 minutes, and 30 seconds
EnableWebCache(New TimeSpan(1, 30, 30))
' Make an initial request to the website with a parse method
Me.Request("http://www.Website.com", Parse)
End Sub
IronWebScraper에는 엔진 시작 프로세스 이름을 Start(CrawlID)를 사용하여 설정함으로써 코드를 재시작한 후에도 스크래핑을 계속할 수 있는 기능이 있습니다.
static void Main(string[] args)
{
// Create an object from the Scraper class
EngineScraper scrape = new EngineScraper();
// Start the scraping process with the specified crawl ID
scrape.Start("enginestate");
}
static void Main(string[] args)
{
// Create an object from the Scraper class
EngineScraper scrape = new EngineScraper();
// Start the scraping process with the specified crawl ID
scrape.Start("enginestate");
}
Shared Sub Main(ByVal args() As String)
' Create an object from the Scraper class
Dim scrape As New EngineScraper()
' Start the scraping process with the specified crawl ID
scrape.Start("enginestate")
End Sub
실행 요청과 응답이 작업 디렉토리 내의 SavedState 폴더에 저장됩니다.
스로틀링
도메인별 최소 및 최대 연결 수와 연결 속도를 제어할 수 있습니다.
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Set the total number of allowed open HTTP requests (threads)
this.MaxHttpConnectionLimit = 80;
// Set minimum polite delay (pause) between requests to a given domain or IP address
this.RateLimitPerHost = TimeSpan.FromMilliseconds(50);
// Set the allowed number of concurrent HTTP requests (threads) per hostname or IP address
this.OpenConnectionLimitPerHost = 25;
// Do not obey the robots.txt files
this.ObeyRobotsDotTxt = false;
// Makes the WebScraper intelligently throttle requests not only by hostname, but also by host servers' IP addresses
this.ThrottleMode = Throttle.ByDomainHostName;
// Make an initial request to the website with a parse method
this.Request("https://www.Website.com", Parse);
}
public override void Init()
{
// Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey";
// Set the logging level to capture all logs
this.LoggingLevel = WebScraper.LogLevel.All;
// Assign the working directory for the output files
this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
// Set the total number of allowed open HTTP requests (threads)
this.MaxHttpConnectionLimit = 80;
// Set minimum polite delay (pause) between requests to a given domain or IP address
this.RateLimitPerHost = TimeSpan.FromMilliseconds(50);
// Set the allowed number of concurrent HTTP requests (threads) per hostname or IP address
this.OpenConnectionLimitPerHost = 25;
// Do not obey the robots.txt files
this.ObeyRobotsDotTxt = false;
// Makes the WebScraper intelligently throttle requests not only by hostname, but also by host servers' IP addresses
this.ThrottleMode = Throttle.ByDomainHostName;
// Make an initial request to the website with a parse method
this.Request("https://www.Website.com", Parse);
}
Public Overrides Sub Init()
' Set the license key for IronWebScraper
License.LicenseKey = "LicenseKey"
' Set the logging level to capture all logs
Me.LoggingLevel = WebScraper.LogLevel.All
' Assign the working directory for the output files
Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
' Set the total number of allowed open HTTP requests (threads)
Me.MaxHttpConnectionLimit = 80
' Set minimum polite delay (pause) between requests to a given domain or IP address
Me.RateLimitPerHost = TimeSpan.FromMilliseconds(50)
' Set the allowed number of concurrent HTTP requests (threads) per hostname or IP address
Me.OpenConnectionLimitPerHost = 25
' Do not obey the robots.txt files
Me.ObeyRobotsDotTxt = False
' Makes the WebScraper intelligently throttle requests not only by hostname, but also by host servers' IP addresses
Me.ThrottleMode = Throttle.ByDomainHostName
' Make an initial request to the website with a parse method
Me.Request("https://www.Website.com", Parse)
End Sub
스로틀링 속성
MaxHttpConnectionLimit
허용된 총 HTTP 요청 수(스레드)RateLimitPerHost
특정 도메인 또는 IP 주소에 대한 요청 간 최소한의 지연 시간(밀리초)OpenConnectionLimitPerHost
호스트 이름당 허용되는 동시 HTTP 요청(스레드) 수ThrottleMode
웹 스크래퍼가 호스트 이름뿐만 아니라 호스트 서버의 IP 주소로도 요청 속도를 지능적으로 조절할 수 있도록 합니다. 이는 스크랩한 도메인이 여러 개 같은 컴퓨터에 호스팅되는 경우를 대비한 예의 있는 표현입니다.
IronWebscraper 시작하기
!{--010011000100100101000010010100100100000101010010010110010101111101010011010101000100000101010010101000101111101010001010010010010010100000101001100010111110100001001001001100010011110100001101001011--}
자주 묻는 질문
C#에서 로그인이 필요한 웹사이트에서 사용자를 어떻게 인증할 수 있나요?
HttpIdentity 기능을 사용하여 IronWebScraper에서 NetworkDomain, NetworkUsername, NetworkPassword 같은 속성을 설정하여 사용자를 인증할 수 있습니다.
개발 중 웹 캐시를 사용하는 이점은 무엇인가요?
웹 캐시 기능은 요청된 페이지를 캐시하여 재사용할 수 있으며, 개발 및 테스트 단계에서 특히 유용하게 사용할 수 있습니다. 이는 살아있는 웹사이트에 대한 반복적인 연결을 피하여 시간과 자원을 절약합니다.
웹 스크래핑에서 여러 로그인 세션을 어떻게 관리할 수 있나요?
IronWebScraper는 독특한 사용자 자격 증명과 브라우저 엔진 수천 개를 사용 가능하게 하여 여러 로그인 세션을 시뮬레이트할 수 있습니다. 이는 웹사이트가 스크래퍼를 탐지하고 차단하는 것을 방지합니다.
웹 스크래핑에서 고급 속도 제한 옵션은 무엇인가요?
IronWebScraper는 ThrottleMode 설정을 제공하여 호스트 이름과 IP 주소를 기반으로 요청 제한을 지능적으로 관리하며, 공유 호스팅 환경과의 존중있는 상호 작용을 보장합니다.
IronWebScraper와 함께 프록시를 어떻게 사용할 수 있나요?
프록시를 사용하려면 프록시 배열을 정의하고 IronWebScraper에서 HttpIdentity 인스턴스와 연결하여 요청을 다른 IP 주소를 통해 라우팅하여 익명성과 액세스 제어를 가능하게 합니다.
서버 과부하를 방지하기 위해 IronWebScraper는 요청 지연을 어떻게 처리하나요?
IronWebScraper의 RateLimitPerHost 설정은 특정 도메인 또는 IP 주소에 대한 요청 간 최소 지연 시간을 지정하여 요청을 간격을 두어 서버 과부하를 방지합니다.
중단 후 웹 스크래핑을 재개할 수 있나요?
네, IronWebScraper는 Start(CrawlID) 메서드를 사용하여 중단 후 스크래핑을 재개할 수 있으며, 이는 실행 상태를 저장하고 마지막 저장 지점부터 시작합니다.
웹 스크래퍼에서 동시 HTTP 연결 수를 어떻게 제어할 수 있나요?
IronWebScraper에서 MaxHttpConnectionLimit 속성을 설정하여 허용된 열린 HTTP 요청 총수를 제어할 수 있으며, 이는 서버 부하와 자원 관리를 돕습니다.
웹 스크래핑 활동을 기록하는 데 어떤 옵션이 있나요?
IronWebScraper는 LoggingLevel 속성을 사용하여 기록 수준을 설정할 수 있으며, 이는 스크래핑 작업 중 세부 분석 및 문제 해결을 위한 포괄적인 로깅을 가능하게 합니다.

