Webscraping in C
¿Qué es IronWebScraper?
IronWebScraper es una biblioteca de clases y un framework para C# y la plataforma de programación .NET que permite a los desarrolladores leer sitios web de manera programática y extraer su contenido. Esto es ideal para la ingeniería inversa de sitios web o intranets existentes y convertirlos de nuevo en bases de datos o datos JSON. También es útil para descargar grandes volúmenes de documentos de internet.
En muchos aspectos, Iron Web Scraper es similar a la biblioteca Scrapy for Python, pero aprovecha las ventajas de C#, en particular su capacidad de avanzar paso a paso por el código mientras el proceso de web scraping está en progreso y depurar.
Instalación
Su primer paso será instalar Iron Web Scraper, lo cual puede hacer desde NuGet o descargando el DLL desde nuestro sitio web.
Todas las clases que necesitará se pueden encontrar en el espacio de nombres de Iron Web Scraper.
Install-Package IronWebScraper
Casos de uso populares
Migración de sitios web a bases de datos
IronWebScraper proporciona las herramientas y métodos para permitirle re-ingeniar sus sitios web de regreso a bases de datos estructuradas. Esta tecnología es útil cuando se migra contenido de sitios web e intranets heredados a su nueva aplicación C#.
Migración de sitios web
Poder extraer fácilmente el contenido de un sitio web parcial o completo en C# reduce el tiempo y el costo implicados en migrar o actualizar recursos de sitios web e intranets. Esto puede ser significativamente más eficiente que las transformaciones directas de SQL, ya que aplana los datos a lo que se puede ver en cada página web y no requiere que se entiendan las estructuras de datos SQL anteriores ni construir consultas SQL complejas.
Población de índices de búsqueda
Iron Web Scraper puede apuntar a su propio sitio web o intranet para leer datos estructurados, leer cada página y extraer los datos correctos para que un motor de búsqueda dentro de su organización se pueda poblar con precisión.
IronWebScraper es una herramienta ideal para extraer contenido para su índice de búsqueda. Una aplicación de búsqueda como IronSearch puede leer contenido estructurado de IronWebScraper para construir un potente sistema de búsqueda empresarial.
Usando Iron Webscraper
Para aprender a usar Iron Web Scraper, es mejor mirar ejemplos. Este ejemplo básico crea una clase para extraer títulos de un blog de sitio web.
using IronWebScraper;
namespace WebScrapingProject
{
class MainClass
{
public static void Main(string [] args)
{
var scraper = new BlogScraper();
scraper.Start();
}
}
class BlogScraper : WebScraper
{
// Initialize scraper settings and make the first request
public override void Init()
{
// Set logging level to show all log messages
this.LoggingLevel = WebScraper.LogLevel.All;
// Request the initial page to start scraping
this.Request("https://ironpdf.com/blog/", Parse);
}
// Method to handle parsing of the page response
public override void Parse(Response response)
{
// Loop through each blog post title link found by CSS selector
foreach (var title_link in response.Css("h2.entry-title a"))
{
// Clean and extract the title text
string strTitle = title_link.TextContentClean;
// Store the extracted title for later use
Scrape(new ScrapedData() { { "Title", strTitle } });
}
// Check if there is a link to the previous post page and if exists, follow it
if (response.CssExists("div.prev-post > a[href]"))
{
// Get the URL for the next page
var next_page = response.Css("div.prev-post > a[href]")[0].Attributes["href"];
// Request the next page to continue scraping
this.Request(next_page, Parse);
}
}
}
}
using IronWebScraper;
namespace WebScrapingProject
{
class MainClass
{
public static void Main(string [] args)
{
var scraper = new BlogScraper();
scraper.Start();
}
}
class BlogScraper : WebScraper
{
// Initialize scraper settings and make the first request
public override void Init()
{
// Set logging level to show all log messages
this.LoggingLevel = WebScraper.LogLevel.All;
// Request the initial page to start scraping
this.Request("https://ironpdf.com/blog/", Parse);
}
// Method to handle parsing of the page response
public override void Parse(Response response)
{
// Loop through each blog post title link found by CSS selector
foreach (var title_link in response.Css("h2.entry-title a"))
{
// Clean and extract the title text
string strTitle = title_link.TextContentClean;
// Store the extracted title for later use
Scrape(new ScrapedData() { { "Title", strTitle } });
}
// Check if there is a link to the previous post page and if exists, follow it
if (response.CssExists("div.prev-post > a[href]"))
{
// Get the URL for the next page
var next_page = response.Css("div.prev-post > a[href]")[0].Attributes["href"];
// Request the next page to continue scraping
this.Request(next_page, Parse);
}
}
}
}
Imports IronWebScraper
Namespace WebScrapingProject
Friend Class MainClass
Public Shared Sub Main(ByVal args() As String)
Dim scraper = New BlogScraper()
scraper.Start()
End Sub
End Class
Friend Class BlogScraper
Inherits WebScraper
' Initialize scraper settings and make the first request
Public Overrides Sub Init()
' Set logging level to show all log messages
Me.LoggingLevel = WebScraper.LogLevel.All
' Request the initial page to start scraping
Me.Request("https://ironpdf.com/blog/", AddressOf Parse)
End Sub
' Method to handle parsing of the page response
Public Overrides Sub Parse(ByVal response As Response)
' Loop through each blog post title link found by CSS selector
For Each title_link In response.Css("h2.entry-title a")
' Clean and extract the title text
Dim strTitle As String = title_link.TextContentClean
' Store the extracted title for later use
Scrape(New ScrapedData() From {
{ "Title", strTitle }
})
Next title_link
' Check if there is a link to the previous post page and if exists, follow it
If response.CssExists("div.prev-post > a[href]") Then
' Get the URL for the next page
Dim next_page = response.Css("div.prev-post > a[href]")(0).Attributes("href")
' Request the next page to continue scraping
Me.Request(next_page, AddressOf Parse)
End If
End Sub
End Class
End Namespace
Para extraer un sitio web específico, tendremos que crear nuestra propia clase para leer ese sitio web. Esta clase extenderá Web Scraper. Agregaremos algunos métodos a esta clase, incluido Init, donde podemos establecer configuraciones iniciales e iniciar la primera solicitud, que a su vez provocará una reacción en cadena donde se raspará todo el sitio web.
También debemos agregar al menos un método Parse. Los métodos Parse leen páginas web que han sido descargadas de internet y utilizan selectores CSS similares a jQuery para seleccionar contenido y extraer el texto y/o las imágenes relevantes para su uso.
Dentro de un método Parse, también podemos especificar qué hipervínculos deseamos que el rastreador continúe siguiendo y cuáles ignorará.
Podemos usar el método Scrape para extraer cualquier dato y volcarlo en un formato de archivo conveniente con estilo JSON para su uso posterior.
Avanzando
Para obtener más información sobre Iron Web Scraper, le recomendamos que lea la Documentación de referencia de la API y, a continuación, comience a consultar los ejemplos de la sección de tutoriales de nuestra documentación.
El próximo ejemplo que le recomendamos ver es el ejemplo de web scraping de "blog" en C#, donde aprendemos cómo podríamos extraer el contenido de texto de un blog, como un blog de WordPress. Esto podría ser muy útil en una migración de sitio.
A partir de ahí, podría pasar a ver otros ejemplos del tutorial de webscraping avanzado donde podemos ver conceptos como sitios web con muchos tipos diferentes de páginas, sitios web de comercio electrónico, y también cómo usar múltiples proxies, identidades e inicios de sesión al extraer datos de internet.

