Erweiterte Web-Scraping-Funktionen in C#
HttpIdentity-Funktion
Einige Webseitensysteme erfordern, dass der Benutzer angemeldet ist, um den Inhalt anzuzeigen; In diesem Fall, können wir ein HttpIdentity verwenden. So können Sie es einrichten:
// 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)Eine der beeindruckendsten und leistungsstärksten Funktionen in IronWebScraper ist die Fähigkeit, Tausende einzigartiger Benutzeranmeldeinformationen und/oder Browser-Engines zu verwenden, um unter Verwendung mehrerer Anmeldesitzungen Websites zu täuschen oder zu scrapen.
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 SubSie haben mehrere Eigenschaften, die Ihnen unterschiedliche Verhaltensweisen ermöglichen, um zu verhindern, dass Websites Sie blockieren.
Einige dieser Eigenschaften umfassen:
NetworkDomain: Die Netzwerkdomäne, die für die Benutzerauthentifizierung verwendet werden soll. Unterstützt Windows-, NTLM-, Kerberos-, Linux-, BSD- und Mac OS X-Netzwerke. Muss mitNetworkUsernameundNetworkPasswordverwendet werden.NetworkUsername: Der Netzwerk/HTTP-Benutzername, der für die Benutzerauthentifizierung verwendet werden soll. Unterstützt HTTP-, Windows-Netzwerke, NTLM-, Kerberos-, Linux-, BSD- und Mac OS-Netzwerke.NetworkPassword: Das Netzwerk/HTTP-Passwort, das für die Benutzerauthentifizierung verwendet werden soll. Unterstützt HTTP-, Windows-Netzwerke, NTLM-, Kerberos-, Linux-, BSD- und Mac OS-Netzwerke.Proxy: Um die Proxy-Einstellungen festzulegen.UserAgent: Um eine Browser-Engine festzulegen (z.B., Chrome Desktop, Chrome Mobile, Chrome Tablet, IE und Firefox, etc.).HttpRequestHeaders: Für benutzerdefinierte Header-Werte, die mit dieser Identität verwendet werden, wird ein WörterbuchobjektDictionary<string, string>akzeptiert.UseCookies: Verwendung von Cookies aktivieren/deaktivieren.
IronWebScraper führt den Scraper unter Verwendung zufälliger Identitäten aus. Wenn wir die Verwendung einer bestimmten Identität zum Parsen einer Seite angeben müssen, können wir dies tun:
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 SubAktivieren der Web-Cache-Funktion
Diese Funktion wird verwendet, um angeforderte Seiten zu cachen. Sie wird häufig in den Entwicklungs- und Testphasen verwendet, um Entwicklern zu ermöglichen, erforderliche Seiten für die Wiederverwendung nach der Aktualisierung des Codes zwischenzuspeichern. Das ermöglicht es Ihnen, Ihren Code auf zwischengespeicherten Seiten auszuführen, nachdem Sie Ihren Webscraper neu gestartet haben, ohne jedes Mal die Verbindung zur Live-Website herstellen zu müssen (Aktions-Wiedergabe).
Sie können es in der Init()-Methode verwenden:
// 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))Es wird Ihre gecachten Daten im WebCache-Ordner unter dem Arbeitsverzeichnis speichern.
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 hat auch Funktionen, mit denen Ihr Motor nach dem Neustart des Codes das Scraping fortsetzen kann, indem der Startprozessname des Motors mit Start(CrawlID) gesetzt wird.
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 SubDie Ausführungsanforderung und Antwort werden im SavedState-Ordner innerhalb des Arbeitsverzeichnisses gespeichert.
Drosselung
Wir können die minimalen und maximalen Verbindungszahlen und die Verbindungsgeschwindigkeit pro Domain steuern.
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 SubDrosselungseigenschaften
MaxHttpConnectionLimitGesamtanzahl erlaubter offener HTTP-Anfragen (Threads)RateLimitPerHostMinimale höfliche Verzögerung oder Pause (in Millisekunden) zwischen Anfragen an eine bestimmte Domain oder IP-AdresseOpenConnectionLimitPerHostErlaubte Anzahl gleichzeitiger HTTP-Anfragen (Threads) pro HostnameThrottleModeLässt den WebScraper intelligent Anfragen drosseln, nicht nur nach Hostname, sondern auch nach den IP-Adressen der Hostserver. Das ist höflich, falls mehrere gescrapte Domains auf derselben Maschine gehostet werden.
Fangen Sie mit IronWebScraper an
Beginnen Sie noch heute, IronWebScraper in Ihrem Projekt mit einer kostenlosen Testversion zu verwenden.
Häufig gestellte Fragen
Was ist der Zweck der Nutzung der HttpIdentity-Funktion in IronWebScraper?
Die HttpIdentity-Funktion in IronWebScraper ermöglicht es Benutzern, verschiedene Benutzeranmeldedaten und Browser-Engines zu simulieren, um Beschränkungen beim Zugriff auf Inhalte durch die Simulation mehrerer Anmeldesitzungen zu umgehen.
Wie kann man das Web-Caching in IronWebScraper aktivieren?
Web-Caching kann in IronWebScraper mit der Methode 'EnableWebCache()' aktiviert werden. Dies ermöglicht es Entwicklern, angeforderte Seiten zu cachen, die insbesondere während der Entwicklungs- und Testphasen wiederverwendet werden können, ohne wiederholt eine Verbindung zur Website herstellen zu müssen.
Was ist der Vorteil der Aktivierung von Throttling in IronWebScraper?
Die Aktivierung von Throttling in IronWebScraper hilft, die Anzahl und Geschwindigkeit der Verbindungen zu Domains zu verwalten, um die Wahrscheinlichkeit zu verringern, wegen zu vieler Anfragen in kurzer Zeit blockiert zu werden. Es sorgt für einen höflichen und effizienten Scraping-Prozess, indem Anfragen über die Zeit verteilt werden.
Kann IronWebScraper das Scraping fortsetzen, wenn der Prozess neu gestartet wird?
Ja, IronWebScraper kann Scraping-Prozesse fortsetzen, nachdem diese neu gestartet wurden, indem der aktuelle Stand mit dem Befehl 'Start(CrawlID)' gespeichert wird, was ein Fortsetzen von dem Punkt ermöglicht, an dem es aufgehört hat.
Welche Verwendung hat das Setzen der 'UseCookies'-Eigenschaft in HttpIdentity?
Die 'UseCookies'-Eigenschaft in HttpIdentity ermöglicht es IronWebScraper, Cookies während Webscraping-Sitzungen zu verwalten, sodass der Status zwischen Anfragen aufrechterhalten werden kann und möglicherweise bestimmte Einschränkungen umgangen werden, die von Websites basierend auf Sitzungsdaten festgelegt werden.
Welche Funktionen bieten die neuen HttpIdentity-Objekte beim Webscraping?
Die HttpIdentity-Objekte in IronWebScraper ermöglichen es Ihnen, Benutzeragenten, Proxys und Authentifizierungsdaten zu steuern und bieten so anspruchsvolle Optionen zur Imitation von Benutzerverhalten und zum Zugriff auf Webinhalte, die auf unterschiedliche Szenarien zugeschnitten sind.
Wie hilft die 'RateLimitPerHost'-Eigenschaft beim Webscraping?
Die 'RateLimitPerHost'-Eigenschaft stellt sicher, dass es eine Mindestverzögerung zwischen ausgehenden Anfragen zu derselben Domain gibt, was verhindert, dass der Scraper den Server überfordert, und so das Risiko einer IP-Sperre verringert.
Welche Vorteile hat die Verwendung mehrerer HttpIdentity-Instanzen in einer einzigen Scraping-Aufgabe?
Die Verwendung mehrerer HttpIdentity-Instanzen ermöglicht es IronWebScraper, verschiedene Identitäten für Anfragen durchzuschalten, wodurch die Last auf verschiedene Anmeldedaten und Browser-Engines verteilt wird. Dies kann helfen, die Erkennung zu vermeiden und die Erfolgsrate von Scraping-Aufgaben zu erhöhen.
Warum ist es wichtig, das 'WorkingDirectory' in IronWebScraper festzulegen?
Durch das Festlegen des 'WorkingDirectory' in IronWebScraper wird angegeben, wo Ausgabedateien, zwischengespeicherte Daten und Statusinformationen gespeichert werden. Es ist entscheidend für die Organisation der Daten und dafür, dass der Scraper während seiner Operationen Ressourcen korrekt zugreift und speichert.
Kann IronWebScraper ohne ständige Verbindung zu einer Live-Website arbeiten?
Ja, IronWebScraper kann arbeiten, indem es seine Webcache-Funktion nutzt, die es ihm erlaubt, Aktionen auf zwischengespeicherten Seiten auszuführen, ohne wiederholt eine Verbindung zur Live-Website herzustellen, was somit schnellere Test- und Entwicklungszyklen ermöglicht.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.