Webscraping in C
Czym jest IronWebScraper?
IronWebScraper to biblioteka klas i framework dla C# i platformy programistycznej .NET, która pozwala programistom programowo czytać strony internetowe i wyodrębniać ich zawartość. To idealne rozwiązanie do inżynierii odwrotnej stron internetowych lub istniejących intranetów i przekształcania ich z powrotem w bazy danych lub dane JSON. Jest również przydatne do pobierania dużych ilości dokumentów z internetu.
Pod wieloma względami IronWebScraper jest podobny do biblioteki Scrapy dla Pythona, ale korzysta z zalet C#, w szczególności z jego zdolności do przechodzenia przez kod podczas trwania procesu web scrapingu i debugowania.
Instalacja
Twoim pierwszym krokiem będzie zainstalowanie IronWebScraper, co możesz zrobić z NuGet lub pobierając pliki DLL z naszej strony internetowej.
Wszystkie potrzebne ci klasy można znaleźć w przestrzeni nazw IronWebScraper.
Install-Package IronWebScraper
Popularne przypadki użycia
Migracja stron internetowych do baz danych
IronWebScraper dostarcza narzędzi i metod, które pozwalają ci przekształcić swoje strony internetowe z powrotem w strukturalne bazy danych. Ta technologia jest użyteczna podczas migracji treści ze starszych stron internetowych i intranetów do twojej nowej aplikacji C#.
Migracja stron internetowych
Możliwość łatwego wyodrębnienia zawartości częściowej lub pełnej strony internetowej w C# redukuje czas i koszty związane z migracją lub unowocześnianiem zasobów stron internetowych i intranetów. Może być to znacznie bardziej efektywne niż bezpośrednie transformacje SQL, ponieważ spłaszcza dane do tego, co może być widoczne na każdej stronie i nie wymaga zrozumienia poprzednich struktur danych SQL ani budowy skomplikowanych zapytań SQL.
Wypełnianie indeksów wyszukiwania
IronWebScraper może być kierowany na twoją stronę internetową lub intranet, aby czytać dane strukturalne, czytać każdą stronę i wyodrębniać poprawne dane, tak aby silnik wyszukiwania w twojej organizacji mógł zostać dokładnie zapełniony.
IronWebScraper to idealne narzędzie do pozyskiwania treści dla twojego indeksu wyszukiwarki. Aplikacja do wyszukiwania, taka jak IronSearch, może czytać strukturalne treści z IronWebScraper, aby zbudować potężny system wyszukiwania dla przedsiębiorstw.
Korzystanie z IronWebscraper
Aby dowiedzieć się, jak używać IronWebScraper, najlepiej jest spojrzeć na przykłady. Ten podstawowy przykład tworzy klasę do pozyskiwania tytułów z bloga internetowego.
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
Aby pozyskać treści z konkretnej strony internetowej, będziemy musieli stworzyć własną klasę do czytania tej strony. Ta klasa będzie rozszerzać Web Scraper. Dodamy do tej klasy kilka metod, w tym Init, w której możemy ustawić początkowe parametry i wysłać pierwsze żądanie, co z kolei spowoduje reakcję łańcuchową, w wyniku której cała strona internetowa zostanie zeskrobana.
Musimy również dodać co najmniej jedną metodę Parse. Metody parsowania czytają strony internetowe które zostały pobrane z internetu i używają selektorów CSS podobnych do jQuery, aby wybrać treść i wyodrębnić odpowiedni tekst i/lub obrazy do wykorzystania.
W ramach metody Parse możemy również określić, które hiperłącza mają być nadal śledzone przez robota indeksującego, a które mają być ignorowane.
Możemy użyć metody Scrape, aby wyodrębnić dowolne dane i zapisać je w dogodnym formacie pliku w stylu JSON do późniejszego użycia.
Ruszając naprzód
Aby dowiedzieć się więcej o IronWebScraper, zalecamy przeczytanie Dokumentacji Referencyjnej API, a następnie przestudiowanie przykładów w sekcji tutoriali naszej dokumentacji.
Kolejny przykład, który polecamy ci zbadać, to C# "blog" przykład web scrapingu, w którym uczymy się, jak można wyciągnąć treść tekstową z bloga, takiego jak blog WordPress. Może to być bardzo przydatne przy migracji witryny.
Stamtąd możesz przejść dalej i spojrzeć na inne zaawansowane tutoriale web scrapingu, gdzie możemy przyjrzeć się koncepcjom stron internetowych z wieloma różnymi typami stron, witrynom e-commerce a także, jak korzystać z wielu serwerów proxy, tożsamości i logowań podczas pozyskiwania danych z internetu.

