Fonctionnalités avancées de web scraping en C

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

Fonctionnalité HttpIdentity

Certains systèmes de sites web exigent que l'utilisateur soit connecté pour consulter le contenu ; dans ce cas, nous pouvons utiliser un HttpIdentity . Voici comment vous pouvez le configurer :

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

L'une des fonctionnalités les plus impressionnantes et puissantes d'IronWebScraper est la possibilité d'utiliser des milliers d'identifiants d'utilisateurs uniques et/ou de moteurs de navigateur pour usurper ou extraire des données de sites Web à l'aide de plusieurs sessions de connexion.

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

Vous disposez de plusieurs propriétés vous permettant d'adopter différents comportements, empêchant ainsi les sites web de vous bloquer.

Certaines de ces propriétés comprennent :

  • NetworkDomain : Le domaine réseau à utiliser pour l'authentification des utilisateurs. Compatible avec les réseaux Windows, NTLM, Kerberos, Linux, BSD et Mac OS X. Doit être utilisé avec NetworkUsername et NetworkPassword .
  • NetworkUsername : Le nom d'utilisateur réseau/http à utiliser pour l'authentification de l'utilisateur. Prend en charge HTTP, les réseaux Windows, NTLM, Kerberos, les réseaux Linux, les réseaux BSD et Mac OS.
  • NetworkPassword : Le mot de passe réseau/http à utiliser pour l'authentification de l'utilisateur. Prend en charge HTTP, les réseaux Windows, NTLM, Kerberos, les réseaux Linux, les réseaux BSD et Mac OS.
  • Proxy : Pour configurer les paramètres du proxy.
  • UserAgent : Pour définir un moteur de navigateur (par exemple, Chrome desktop, Chrome mobile, Chrome tablet, IE, Firefox, etc.).
  • HttpRequestHeaders : Pour les valeurs d'en-tête personnalisées qui seront utilisées avec cette identité, il accepte un objet Dictionary<string, string> .
  • UseCookies : Activer/désactiver l'utilisation des cookies.

IronWebScraper exécute le scraper en utilisant des identités aléatoires. Si nous devons spécifier l'utilisation d'une identité particulière pour analyser une page, nous pouvons le faire :

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

Activer la fonction de cache Web

Cette fonctionnalité permet de mettre en cache les pages demandées. Il est souvent utilisé lors des phases de développement et de test, permettant aux développeurs de mettre en cache les pages nécessaires pour les réutiliser après la mise à jour du code. Cela vous permet d'exécuter votre code sur des pages mises en cache après avoir redémarré votre robot d'extraction Web sans avoir besoin de vous connecter au site Web en direct à chaque fois (relecture d'action).

Vous pouvez l'utiliser dans la méthode 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))
$vbLabelText   $csharpLabel

Vos données mises en cache seront enregistrées dans le dossier WebCache situé dans le répertoire de travail.

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

IronWebScraper possède également des fonctionnalités permettant à votre moteur de continuer à extraire des données après le redémarrage du code en définissant le nom du processus de démarrage du moteur à l'aide 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
$vbLabelText   $csharpLabel

La requête d'exécution et la réponse seront enregistrées dans le dossier SavedState situé dans le répertoire de travail.

Étranglement

Nous pouvons contrôler le nombre minimal et maximal de connexions ainsi que la vitesse de connexion par domaine.

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

Propriétés d'étranglement

  • MaxHttpConnectionLimit
    Nombre total de requêtes HTTP ouvertes autorisées (threads)
  • RateLimitPerHost
    Délai ou pause minimale polie (en millisecondes) entre les requêtes adressées à un domaine ou une adresse IP donnée
  • OpenConnectionLimitPerHost
    Nombre de requêtes HTTP simultanées autorisées (threads) par nom d'hôte
  • ThrottleMode
    Permet au WebScraper de limiter intelligemment les requêtes non seulement par nom d'hôte, mais aussi par adresse IP des serveurs hôtes. Cette pratique est courtoise dans le cas où plusieurs domaines extraits seraient hébergés sur la même machine.

Commencez à utiliser IronWebscraper

Commencez à utiliser IronWebScraper dans votre projet aujourd'hui avec un essai gratuit.

Première étape :
green arrow pointer

Questions Fréquemment Posées

Comment puis-je authentifier les utilisateurs sur les sites nécessitant une connexion en C# ?

Vous pouvez utiliser la fonctionnalité HttpIdentity dans IronWebScraper pour authentifier les utilisateurs en configurant des propriétés telles que NetworkDomain, NetworkUsername, et NetworkPassword.

Quel est l'avantage d'utiliser le cache web pendant le développement ?

La fonction de cache web vous permet de mettre en cache les pages demandées pour une réutilisation, ce qui aide à économiser du temps et des ressources en évitant les connexions répétées aux sites en ligne, particulièrement utile pendant les phases de développement et de test.

Comment puis-je gérer plusieurs sessions de connexion dans le scraping web ?

IronWebScraper permet l'utilisation de milliers d'identifiants d'utilisateur uniques et de moteurs de navigateur pour simuler plusieurs sessions de connexion, ce qui aide à prévenir la détection et le blocage du scraper par les sites web.

Quelles sont les options de throttling avancées dans le scraping web ?

IronWebScraper propose un paramètre ThrottleMode qui gère intelligemment le throttling des requêtes en fonction des noms d'hôtes et des adresses IP, garantissant une interaction respectueuse avec les environnements d'hébergement partagé.

Comment puis-je utiliser un proxy avec IronWebScraper ?

Pour utiliser un proxy, définissez un tableau de proxies et associez-les aux instances HttpIdentity dans IronWebScraper, permettant aux requêtes d'être acheminées par différentes adresses IP pour l'anonymat et le contrôle d'accès.

Comment IronWebScraper gère-t-il les délais de requête pour éviter la surcharge du serveur ?

Le paramètre RateLimitPerHost dans IronWebScraper spécifie le délai minimum entre les requêtes vers un domaine ou une adresse IP spécifique, contribuant à prévenir la surcharge du serveur en espaçant les requêtes.

Le scraping web peut-il être repris après une interruption ?

Oui, IronWebScraper peut reprendre le scraping après une interruption en utilisant la méthode Start(CrawlID), qui enregistre l'état d'exécution et reprend à partir du dernier point enregistré.

Comment puis-je contrôler le nombre de connexions HTTP simultanées dans un scraper web ?

Dans IronWebScraper, vous pouvez définir la propriété MaxHttpConnectionLimit pour contrôler le nombre total de requêtes HTTP ouvertes autorisées, aidant à gérer la charge du serveur et les ressources.

Quelles sont les options disponibles pour journaliser les activités de scraping web ?

IronWebScraper vous permet de définir le niveau de journalisation en utilisant la propriété LoggingLevel, permettant une journalisation exhaustive pour une analyse détaillée et un dépannage lors des opérations de scraping.

Darrius Serrant
Ingénieur logiciel Full Stack (WebOps)

Darrius Serrant est titulaire d'un baccalauréat en informatique de l'université de Miami et travaille comme ingénieur marketing WebOps Full Stack chez Iron Software. Attiré par le codage dès son plus jeune âge, il a vu l'informatique comme à la fois mystérieuse et accessible, en faisant le ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 125,527 | Version: 2025.11 vient de sortir