Zaawansowane funkcje web scrapingu w C#
Funkcja HttpIdentity
Niektóre systemy stron internetowych wymagają, aby użytkownik był zalogowany, aby wyświetlić zawartość; w tym przypadku możemy użyć HttpIdentity. Oto jak to skonfigurować:
// 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)' 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)Jedną z najbardziej imponujących i potężnych funkcji w IronWebScraper jest możliwość użycia tysięcy unikalnych danych logowania użytkownika i/lub silników przeglądarek do symulowania lub zbierania danych z witryn korzystając z wielu sesji logowania.
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
Next
' Make an initial request to the website with a parse method
Me.Request("http://www.Website.com", AddressOf Parse)
End SubPublic 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
Next
' Make an initial request to the website with a parse method
Me.Request("http://www.Website.com", AddressOf Parse)
End SubMasz wiele właściwości dających różne zachowania, uniemożliwiając witrynom blokowanie cię.
Niektóre z tych właściwości to:
NetworkDomain: Domenę sieciową do użycia przy uwierzytelnianiu użytkownika. Obsługuje sieci Windows, NTLM, Kerberos, Linux, BSD i Mac OS X. Musi być używane zNetworkUsernameiNetworkPassword.NetworkUsername: Nazwa użytkownika sieciowego/http do użycia przy uwierzytelnianiu użytkownika. Obsługuje HTTP, sieci Windows, NTLM, Kerberos, sieci Linux, sieci BSD i Mac OS.NetworkPassword: Hasło sieciowe/http do użycia przy uwierzytelnianiu użytkownika. Obsługuje HTTP, sieci Windows, NTLM, Kerberos, sieci Linux, sieci BSD i Mac OS.Proxy: Aby ustawić ustawienia proxy.UserAgent: Aby ustawić silnik przeglądarki (np. Chrome desktop, Chrome mobile, Chrome tablet, IE, Firefoks itp.).HttpRequestHeaders: Dla niestandardowych wartości nagłówków, które będą używane z tą tożsamością, akceptuje obiekt słownikaDictionary<string, string>.UseCookies: Włączenie/wyłączenie używania cookies.
IronWebScraper uruchamia scraper korzystając z losowych tożsamości. Jeśli musimy określić użycie konkretnej tożsamości do analizy strony, możemy to zrobić:
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", AddressOf Parse, identity)
End SubPublic 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", AddressOf Parse, identity)
End SubWłącz funkcję pamięci podręcznej
Ta funkcja służy do buforowania żądanych stron. Często używana w fazach rozwoju i testowania, umożliwiając programistom buforowanie wymaganych stron do ponownego użycia po zaktualizowaniu kodu. Umożliwia wykonanie kodu na stronie buforowanej po ponownym uruchomieniu webscrapera bez potrzeby łączenia się z aktywną stroną za każdym razem (action-replay).
Możesz to użyć w metodzie 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))' Enable web cache without an expiration time
EnableWebCache()
' OR enable web cache with a specified expiration time
EnableWebCache(New TimeSpan(1, 30, 30))Zapisze Twoje dane w pamięci podręcznej do folderu WebCache w folderze katalogu roboczego.
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 SubPublic 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 SubIronWebScraper ma również funkcje umożliwiające kontynuowanie skanowania przez Twój silnik po ponownym uruchomieniu kodu przez ustawienie nazwy procesu startowego silnika za pomocą 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");
}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 SubSub 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Żądanie wykonania i odpowiedź zostaną zapisane w folderze SavedState wewnątrz katalogu roboczego.
Regulacja obciążenia
Możemy kontrolować minimalną i maksymalną liczbę połączeń oraz prędkość połączeń na domenę.
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", AddressOf Parse)
End SubPublic 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", AddressOf Parse)
End SubWłaściwości regulacji obciążenia
MaxHttpConnectionLimitCałkowita liczba dozwolonych otwartych żądań HTTP (wątków)RateLimitPerHostMinimalne uprzejme opóźnienie lub pauza (w milisekundach) pomiędzy żądaniami do danej domeny lub adresu IPOpenConnectionLimitPerHostDozwolona liczba równoczesnych żądań HTTP (wątków) na nazwę hostaThrottleModeWebScraper inteligentnie reguluje żądania nie tylko według nazwy hosta, ale także według adresów IP serwerów hosta. Jest to uprzejme w przypadku, gdy wiele skanowanych domen jest hostowanych na tej samej maszynie.
Rozpocznij korzystanie z IronWebScraper
Rozpocznij korzystanie z IronWebScraper we własnym projekcie już dziś z darmową wersją próbną.
Najczęściej zadawane pytania
Jaki jest cel korzystania z funkcji HttpIdentity w IronWebScraper?
Funkcja HttpIdentity w IronWebScraper pozwala użytkownikom na naśladowanie różnych poświadczeń użytkowników i silników przeglądarek do webscrapingu, pomagając w ominięciu ograniczeń dostępu do treści poprzez symulację wielu sesji logowania.
Jak można włączyć buforowanie sieciowe w IronWebScraper?
Buforowanie sieciowe można włączyć w IronWebScraper za pomocą metody 'EnableWebCache()'. Pozwala ona programistom na buforowanie żądanych stron, które mogą być ponownie wykorzystane, szczególnie podczas fazy rozwoju i testowania, bez konieczności ciągłego łączenia się z witryną.
Jaka jest zaleta włączenia ograniczania przepustowości w IronWebScraper?
Włączenie ograniczania przepustowości w IronWebScraper pomaga zarządzać liczbą i prędkością połączeń z domenami, zmniejszając prawdopodobieństwo zablokowania za zbyt wiele zapytań w krótkim czasie. Zapewnia uprzejmy i efektywny proces scrapowania poprzez rozłożenie zapytań w czasie.
Czy IronWebScraper może kontynuować scrapowanie, jeśli proces zostanie ponownie uruchomiony?
Tak, IronWebScraper może kontynuować procesy scrapowania po ich ponownym uruchomieniu, zapisując bieżący stan za pomocą komendy 'Start(CrawlID)', co pozwala na wznowienie od momentu, w którym zostało przerwane.
Do czego służy ustawienie właściwości 'UseCookies' w HttpIdentity?
Właściwość 'UseCookies' w HttpIdentity pozwala IronWebScraper na zarządzanie ciasteczkami podczas sesji webscrapingu, umożliwiając utrzymanie stanu między zapytaniami i potencjalne ominięcie pewnych ograniczeń narzucanych przez witryny na podstawie danych sesyjnych.
Jakie funkcje zapewniają nowe obiekty HttpIdentity w webscrapingu?
Obiekty HttpIdentity w IronWebScraper pozwalają na kontrolowanie agentów użytkownika, proxy i poświadczeń uwierzytelniających, oferując zaawansowane opcje naśladowania zachowań użytkowników i dostępu do treści internetowych dostosowanych do różnych scenariuszy.
W jaki sposób właściwość 'RateLimitPerHost' pomaga w webscrapingu?
Właściwość 'RateLimitPerHost' zapewnia minimalne opóźnienie między wysyłanymi zapytaniami do tej samej domeny, co pomaga zapobiec przeciążeniu serwera przez scraper, zmniejszając ryzyko blokady IP.
Jakie są korzyści z użycia wielu instancji HttpIdentity w jednym zadaniu scrapingu?
Użycie wielu instancji HttpIdentity pozwala IronWebScraper na cykliczne wykorzystywanie różnych tożsamości dla zapytań, rozkładając obciążenie na różne poświadczenia i silniki przeglądarek, co może pomóc w uniknięciu wykrycia i zwiększeniu skuteczności zadań scrapingu.
Dlaczego ważne jest ustawienie 'WorkingDirectory' w IronWebScraper?
Ustawienie 'WorkingDirectory' w IronWebScraper określa, gdzie będą przechowywane pliki wyjściowe, dane buforowane i informacje o stanie. Jest to kluczowe dla organizacji danych i zapewnienia prawidłowego dostępu i zapisu zasobów przez scraper podczas jego operacji.
Czy IronWebScraper może działać bez ciągłego łączenia się z aktywną witryną?
Tak, IronWebScraper może działać, wykorzystując funkcję buforowania sieciowego, która pozwala na wykonywanie działań na buforowanych stronach bez wielokrotnego łączenia się z aktywną witryną, co ułatwia szybsze cykle testowania i rozwoju.
Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podręczników.