Funciones avanzadas de Webscraping

Darrius Serrant
Darrius Serrant
25 de enero, 2023
Actualizado 10 de diciembre, 2024
Compartir:
This article was translated from English: Does it need improvement?
Translated
View the article in English

Función HttpIdentity

Algunos sistemas de sitios web exigen que el usuario inicie sesión para ver el contenido; en este caso podemos utilizar una HttpIdentity: -

HttpIdentity id = new HttpIdentity();
id.NetworkUsername = "username";
id.NetworkPassword = "pwd";
Identities.Add(id); 
HttpIdentity id = new HttpIdentity();
id.NetworkUsername = "username";
id.NetworkPassword = "pwd";
Identities.Add(id); 
Dim id As New HttpIdentity()
id.NetworkUsername = "username"
id.NetworkPassword = "pwd"
Identities.Add(id)
$vbLabelText   $csharpLabel

Una de las características más impresionantes y poderosas de IronWebScraper es la capacidad de utilizar miles de datos únicos (credenciales de usuario y/o motores de navegador) para suplantar o extraer datos de sitios web utilizando sesiones de inicio de sesión múltiples.

public override void Init()
{
    License.LicenseKey = " LicenseKey ";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    var proxies = "IP-Proxy1: 8080,IP-Proxy2: 8081".Split(',');
    foreach (var UA in IronWebScraper.CommonUserAgents.ChromeDesktopUserAgents)
    {
        foreach (var proxy in proxies)
        {
            Identities.Add(new HttpIdentity()
            {
                UserAgent = UA,
                UseCookies = true,
                Proxy = proxy
            });
        }
    }
    this.Request("http://www.Website.com", Parse);
}
public override void Init()
{
    License.LicenseKey = " LicenseKey ";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    var proxies = "IP-Proxy1: 8080,IP-Proxy2: 8081".Split(',');
    foreach (var UA in IronWebScraper.CommonUserAgents.ChromeDesktopUserAgents)
    {
        foreach (var proxy in proxies)
        {
            Identities.Add(new HttpIdentity()
            {
                UserAgent = UA,
                UseCookies = true,
                Proxy = proxy
            });
        }
    }
    this.Request("http://www.Website.com", Parse);
}
Public Overrides Sub Init()
	License.LicenseKey = " LicenseKey "
	Me.LoggingLevel = WebScraper.LogLevel.All
	Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
	Dim proxies = "IP-Proxy1: 8080,IP-Proxy2: 8081".Split(","c)
	For Each UA In IronWebScraper.CommonUserAgents.ChromeDesktopUserAgents
		For Each proxy In proxies
			Identities.Add(New HttpIdentity() With {
				.UserAgent = UA,
				.UseCookies = True,
				.Proxy = proxy
			})
		Next proxy
	Next UA
	Me.Request("http://www.Website.com", Parse)
End Sub
$vbLabelText   $csharpLabel

Dispone de múltiples propiedades para darle diferentes comportamientos, evitando así que los sitios web le bloqueen.

Algunas de estas propiedades: -

  • NetworkDomain : El dominio de red que se utilizará para la autenticación de usuarios. Compatible con redes Windows, NTLM , Keroberos, Linux, BSD y Mac OS X. Debe usarse con (NetworkUsername y NetworkPassword)
  • NetworkUsername : El nombre de usuario de red/HTTP que se usará para la autenticación de usuario. Soporta Http, redes Windows, NTLM , Kerberos , redes Linux, redes BSD y Mac OS.
  • NetworkPassword : La contraseña de red/http que se utilizará para la autenticación del usuario. Soporta Http , redes Windows, NTLM , Keroberos , redes Linux, redes BSD y Mac OS.
  • Proxy: para configurar los ajustes de proxy
  • UserAgent: para configurar el motor del navegador (chrome desktop, chrome mobile, chrome tablet, IE y Firefox, etc.)
  • HttpRequestHeaders: para valores de encabezado personalizados que se utilizarán con esta identidad, y acepta un objeto de diccionario (Dictionary <string, string>)
  • UseCookies : habilitar/deshabilitar el uso de cookies

    IronWebScraper ejecuta el scraper utilizando identidades aleatorias. Si necesitamos especificar el uso de una identidad concreta para analizar una página, podemos hacerlo.

public override void Init()
{
    License.LicenseKey = " LicenseKey ";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    HttpIdentity identity = new HttpIdentity();
    identity.NetworkUsername = "username";
    identity.NetworkPassword = "pwd";
    Identities.Add(id);
    this.Request("http://www.Website.com", Parse, identity);
}
public override void Init()
{
    License.LicenseKey = " LicenseKey ";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    HttpIdentity identity = new HttpIdentity();
    identity.NetworkUsername = "username";
    identity.NetworkPassword = "pwd";
    Identities.Add(id);
    this.Request("http://www.Website.com", Parse, identity);
}
Public Overrides Sub Init()
	License.LicenseKey = " LicenseKey "
	Me.LoggingLevel = WebScraper.LogLevel.All
	Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
	Dim identity As New HttpIdentity()
	identity.NetworkUsername = "username"
	identity.NetworkPassword = "pwd"
	Identities.Add(id)
	Me.Request("http://www.Website.com", Parse, identity)
End Sub
$vbLabelText   $csharpLabel

Activar la función de caché web

Esta función se utiliza para almacenar en caché las páginas solicitadas. Suele utilizarse en las fases de desarrollo y prueba; que permite a los desarrolladores almacenar en caché las páginas necesarias para reutilizarlas tras actualizar el código. Esto te permite ejecutar tu código en páginas en caché después de reiniciar tu scraper web y no necesitar conectarte al sitio web en vivo cada vez (repetición de acción).

Puedes usarlo en el método Init()

EnableWebCache();

O

EnableWebCache(Timespan Expiry);

Guardará los datos en caché en la carpeta WebCache situada bajo la carpeta del directorio de trabajo

public override void Init()
{
    License.LicenseKey = " LicenseKey ";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    EnableWebCache(new TimeSpan(1,30,30));
    this.Request("http://www.WebSite.com", Parse);
}
public override void Init()
{
    License.LicenseKey = " LicenseKey ";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    EnableWebCache(new TimeSpan(1,30,30));
    this.Request("http://www.WebSite.com", Parse);
}
Public Overrides Sub Init()
	License.LicenseKey = " LicenseKey "
	Me.LoggingLevel = WebScraper.LogLevel.All
	Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
	EnableWebCache(New TimeSpan(1,30,30))
	Me.Request("http://www.WebSite.com", Parse)
End Sub
$vbLabelText   $csharpLabel

IronWebScraper también tiene funciones para permitir que tu motor continúe raspando después de reiniciar el código al establecer el nombre del proceso de inicio del motor usando Start(CrawlID)

static void Main(string [] args)
{
    // Create Object From Scraper class
    EngineScraper scrape = new EngineScraper();
    // Start Scraping
    scrape.Start("enginestate");
}
static void Main(string [] args)
{
    // Create Object From Scraper class
    EngineScraper scrape = new EngineScraper();
    // Start Scraping
    scrape.Start("enginestate");
}
Shared Sub Main(ByVal args() As String)
	' Create Object From Scraper class
	Dim scrape As New EngineScraper()
	' Start Scraping
	scrape.Start("enginestate")
End Sub
$vbLabelText   $csharpLabel

La solicitud de ejecución y la respuesta 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()
{
    License.LicenseKey = "LicenseKey";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    // Gets or sets the total number of allowed open HTTP requests (threads)
    this.MaxHttpConnectionLimit = 80;
    // Gets or sets minimum polite delay (pause)between request to a given domain or IP address.
    this.RateLimitPerHost = TimeSpan.FromMilliseconds(50);            
    //     Gets or sets the allowed number of concurrent HTTP requests (threads) per hostname
    //     or IP address. This helps protect hosts against too many requests.
    this.OpenConnectionLimitPerHost = 25;
    this.ObeyRobotsDotTxt = false;
    //     Makes the WebSraper intelligently throttle requests not only by hostname, but
    //     also by host servers' IP addresses. This is polite in-case multiple scraped domains
    //     are hosted on the same machine.
    this.ThrottleMode = Throttle.ByDomainHostName;
    this.Request("https://www.Website.com", Parse);
}
public override void Init()
{
    License.LicenseKey = "LicenseKey";
    this.LoggingLevel = WebScraper.LogLevel.All;
    this.WorkingDirectory = AppSetting.GetAppRoot() + @"\ShoppingSiteSample\Output\";
    // Gets or sets the total number of allowed open HTTP requests (threads)
    this.MaxHttpConnectionLimit = 80;
    // Gets or sets minimum polite delay (pause)between request to a given domain or IP address.
    this.RateLimitPerHost = TimeSpan.FromMilliseconds(50);            
    //     Gets or sets the allowed number of concurrent HTTP requests (threads) per hostname
    //     or IP address. This helps protect hosts against too many requests.
    this.OpenConnectionLimitPerHost = 25;
    this.ObeyRobotsDotTxt = false;
    //     Makes the WebSraper intelligently throttle requests not only by hostname, but
    //     also by host servers' IP addresses. This is polite in-case multiple scraped domains
    //     are hosted on the same machine.
    this.ThrottleMode = Throttle.ByDomainHostName;
    this.Request("https://www.Website.com", Parse);
}
Public Overrides Sub Init()
	License.LicenseKey = "LicenseKey"
	Me.LoggingLevel = WebScraper.LogLevel.All
	Me.WorkingDirectory = AppSetting.GetAppRoot() & "\ShoppingSiteSample\Output\"
	' Gets or sets the total number of allowed open HTTP requests (threads)
	Me.MaxHttpConnectionLimit = 80
	' Gets or sets minimum polite delay (pause)between request to a given domain or IP address.
	Me.RateLimitPerHost = TimeSpan.FromMilliseconds(50)
	'     Gets or sets the allowed number of concurrent HTTP requests (threads) per hostname
	'     or IP address. This helps protect hosts against too many requests.
	Me.OpenConnectionLimitPerHost = 25
	Me.ObeyRobotsDotTxt = False
	'     Makes the WebSraper intelligently throttle requests not only by hostname, but
	'     also by host servers' IP addresses. This is polite in-case multiple scraped domains
	'     are hosted on the same machine.
	Me.ThrottleMode = Throttle.ByDomainHostName
	Me.Request("https://www.Website.com", Parse)
End Sub
$vbLabelText   $csharpLabel

Propiedades de estrangulamiento

  • MaxHttpConnectionLimit


    Número total de solicitudes HTTP abiertas permitidas (hilos)

  • RateLimitPerHost


    Retraso educado mínimo o pausa (en milisegundos) entre solicitudes a un dominio o dirección IP dada

  • OpenConnectionLimitPerHost

    Número permitido de solicitudes HTTP concurrentes (hilos)

  • Modo de Limitación


    Hace que el WebScraper regule inteligentemente las solicitudes no solo por nombre de host, sino también por las direcciones IP de los servidores host. Esto es útil en caso de que varios dominios raspados estén alojados en la misma máquina.


    Comienza con IronWebscraper

    Comience a usar IronWebScraper en su proyecto hoy con una prueba gratuita.

    Primer Paso:
    green arrow pointer

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Informática de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde una edad temprana, veía la computación como algo misterioso y accesible, lo que la convertía en el medio perfecto para la creatividad y la resolución de problemas.

En Iron Software, Darrius disfruta creando cosas nuevas y simplificando conceptos complejos para hacerlos más comprensibles. Como uno de nuestros desarrolladores residentes, también se ha ofrecido como voluntario para enseñar a los estudiantes, compartiendo su experiencia con la próxima generación.

Para Darrius, su trabajo es gratificante porque es valorado y tiene un impacto real.