Funciones avanzadas de web scraping en C#
Función HttpIdentity
Algunos sistemas de sitios web requieren que el usuario inicie sesión para ver el contenido; en este caso, podemos usar un HttpIdentity. Aquí se explica cómo configurarlo:
// 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)Una de las características más impresionantes y poderosas en IronWebScraper es la capacidad de utilizar miles de credenciales de usuario únicas y/o motores de navegador para simular o extraer sitios web usando múltiples sesiones de inicio de sesión.
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 SubTienes múltiples propiedades que te dan diferentes comportamientos, evitando que los sitios web te bloqueen.
Algunas de estas propiedades incluyen:
NetworkDomain: El dominio de red que se usará para la autenticación del usuario. Compatible con Windows, NTLM, Kerberos, Linux, BSD y Mac OS X. Debe usarse conNetworkUsernameyNetworkPassword.NetworkUsername: El nombre de usuario de red/http que se usará para la autenticación del usuario. Compatible con HTTP, redes de Windows, NTLM, Kerberos, redes de Linux, redes de BSD y Mac OS.NetworkPassword: La contraseña de red/http que se usará para la autenticación del usuario. Compatible con HTTP, redes de Windows, NTLM, Kerberos, redes de Linux, redes de BSD y Mac OS.Proxy: Para configurar los ajustes del proxy.UserAgent: Para establecer un motor de navegador (por ejemplo, Chrome de escritorio, Chrome móvil, Chrome tablet, IE y Firefox, etc.).HttpRequestHeaders: Para valores de cabecera personalizados que se usarán con esta identidad, acepta un objeto de diccionarioDictionary<string, string>.UseCookies: Habilitar/deshabilitar el uso de cookies.
IronWebScraper ejecuta el scraper usando identidades aleatorias. Si necesitamos especificar el uso de una identidad específica para analizar una página, podemos hacerlo:
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 SubHabilitar la función de caché web
Esta función almacena en caché las páginas solicitadas. Se utiliza a menudo en las fases de desarrollo y prueba, permitiendo a los desarrolladores almacenar en caché las páginas requeridas para reutilizarlas después de actualizar el código. Esto te permite ejecutar tu código en páginas almacenadas en caché después de reiniciar tu extractor web sin necesidad de conectarte al sitio web en vivo cada vez (repetición de acción).
Puedes usarlo en el método 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))Guardará tus datos en caché en la carpeta WebCache dentro de la carpeta del directorio de trabajo.
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 también tiene funciones para habilitar que tu motor continúe scrapando después de reiniciar el código configurando el nombre del proceso de inicio del motor usando 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 SubLa solicitud y respuesta de ejecución se guardarán en la carpeta SavedState dentro del directorio de trabajo.
Estrangulamiento
Podemos controlar el número mínimo y máximo de conexiones y la velocidad de conexión por dominio.
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 SubPropiedades de estrangulamiento
MaxHttpConnectionLimitNúmero total de solicitudes HTTP abiertas permitidas (hilos)RateLimitPerHostRetraso o pausa educado mínimo (en milisegundos) entre solicitudes a un dominio o dirección IP dadoOpenConnectionLimitPerHostNúmero permitido de solicitudes HTTP concurrentes (hilos) por nombre de hostThrottleModeHace que el WebScraper limite inteligentemente las solicitudes no solo por nombre de host, sino también por direcciones IP de los servidores de host. Esto es educado en caso de que múltiples dominios extraídos estén alojados en la misma máquina.
Comience con IronWebScraper
Empiece a usar IronWebScraper en su proyecto hoy con una prueba gratuita.
Preguntas frecuentes
¿Cuál es el propósito de utilizar la función HttpIdentity en IronWebScraper?
La función HttpIdentity en IronWebScraper permite a los usuarios suplantar diferentes credenciales de usuario y motores de navegador para la extracción web, ayudando a sortear restricciones de acceso a contenido al simular múltiples sesiones de inicio de sesión.
¿Cómo se puede habilitar el almacenamiento en caché web en IronWebScraper?
El almacenamiento en caché web se puede habilitar en IronWebScraper usando el método 'EnableWebCache()'. Esto permite a los desarrolladores almacenar en caché las páginas solicitadas, que se pueden reutilizar, especialmente durante las fases de desarrollo y prueba, sin necesidad de conectarse repetidamente al sitio web.
¿Cuál es la ventaja de habilitar la limitación de velocidad en IronWebScraper?
Habilitar la limitación de velocidad en IronWebScraper ayuda a gestionar la cantidad y velocidad de las conexiones a los dominios, reduciendo la probabilidad de ser bloqueado por hacer demasiadas solicitudes en un período corto. Asegura un proceso de extracción educado y eficiente distribuyendo las solicitudes a lo largo del tiempo.
¿Puede IronWebScraper continuar extrayendo si se reinicia el proceso?
Sí, IronWebScraper puede continuar los procesos de extracción después de reiniciarse guardando el estado actual utilizando el comando 'Start(CrawlID)', que permite reanudar desde donde se dejó.
¿Para qué sirve configurar la propiedad 'UseCookies' en HttpIdentity?
La propiedad 'UseCookies' en HttpIdentity permite a IronWebScraper gestionar cookies durante las sesiones de extracción web, habilitándolo para mantener el estado entre solicitudes y potencialmente sortear ciertas restricciones establecidas por sitios web basadas en datos de sesión.
¿Qué funcionalidades proporcionan los nuevos objetos HttpIdentity en la extracción web?
Los objetos HttpIdentity en IronWebScraper le permiten controlar agentes de usuario, proxies y credenciales de autenticación, habilitando opciones sofisticadas para imitar el comportamiento del usuario y acceder a contenido web adaptado a diferentes escenarios.
¿Cómo ayuda la propiedad 'RateLimitPerHost' en la extracción web?
La propiedad 'RateLimitPerHost' asegura un retraso mínimo entre las solicitudes salientes al mismo dominio, lo que ayuda a prevenir que el extractor sature el servidor, reduciendo así el riesgo de prohibiciones de IP.
¿Cuáles son los beneficios de usar múltiples instancias de HttpIdentity en una sola tarea de extracción?
Usar múltiples instancias de HttpIdentity permite a IronWebScraper rotar a través de diferentes identidades para las solicitudes, distribuyendo la carga a través de diversas credenciales y motores de navegador, lo que puede ayudar a evitar la detección y aumentar la tasa de éxito de las tareas de extracción.
¿Por qué es importante establecer el 'WorkingDirectory' en IronWebScraper?
Establecer el 'WorkingDirectory' en IronWebScraper especifica dónde se almacenarán los archivos de salida, los datos en caché y la información de estado. Es crucial para organizar los datos y asegurarse de que el extractor acceda y guarde los recursos correctamente a lo largo de sus operaciones.
¿Puede IronWebScraper funcionar sin conectarse constantemente a un sitio web en vivo?
Sí, IronWebScraper puede funcionar utilizando su función de caché web, lo que le permite realizar acciones en páginas en caché sin conectarse repetidamente al sitio web en vivo, facilitando así ciclos de prueba y desarrollo más rápidos.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.