在 C# 中進行網頁擷取
IronWebScraper是什麼?
IronWebScraper 是一個適用於 C# 和 .NET 程式設計平台的類別庫和框架,它允許開發人員以程式設計方式讀取網站並提取其內容。 這非常適合對網站或現有內網進行逆向工程,並將其轉換回資料庫或 JSON 資料。 它也可用於從互聯網下載大量文件。
在許多方面,IronWebScraper 與 Python 的 Scrapy 函數庫類似,但利用 C# 的優勢,特別是其能夠在網絡抓取過程中逐步執行代碼並進行調試。
安裝
您的第一步是安裝IronWebScraper,您可以從NuGet或從我們的網站下載DLL來進行安裝。
您需要的所有類都可在 IronWebScraper 命名空間中找到。
常見應用案例
將網站遷移到資料庫
IronWebScraper 提供工具和方法,讓您可以將網站重新設計成結構化資料庫。 當舊網站和內部網路的內容遷移到新的 C# 應用程式時,這項技術非常有用。
網站遷移
能夠輕鬆地在 C# 中提取部分或完整網站的內容,可以減少遷移或升級網站和內網資源所需的時間和成本。 這比直接進行 SQL 轉換要高效得多,因為它將資料簡化為每個網頁上可見的內容,並且不需要理解先前的 SQL 資料結構,也不需要建立複雜的 SQL 查詢。
填充搜尋索引
IronWebScraper 可指向您自己的網站或局域網,以讀取結構化數據,讀取每個頁面,並提取正確的數據,以便貴組織的搜索引擎能夠精確填充。
IronWebScraper 是抓取內容以建立搜尋索引的理想工具。 像 IronSearch 這樣的搜尋應用程式可以從 IronWebScraper 讀取結構化內容,從而建立強大的企業搜尋系統。
使用IronWebScraper
要瞭解如何使用 IronWebScraper,最好查看示例。 這個基本範例創建了一個類,用於從網站部落格中抓取標題。
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
Class MainClass
Public Shared Sub Main(ByVal args As String())
Dim scraper As New BlogScraper()
scraper.Start()
End Sub
End Class
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
' 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 NamespaceImports IronWebScraper
Namespace WebScrapingProject
Class MainClass
Public Shared Sub Main(ByVal args As String())
Dim scraper As New BlogScraper()
scraper.Start()
End Sub
End Class
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
' 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為了抓取特定網站的資料,我們需要建立一個自訂類別來讀取該網站的內容。這個類別將繼承自 Web Scraper 類別。 我們將會在這個類別中添加一些方法,包括Init,其中我們可以設置初始設置並開始第一次請求,這將隨後引發連鎖反應,整個網站將被爬取。
我們還必須至少添加一個Parse方法。 解析方法讀取從互聯網下載的網頁,並使用類似 jQuery 的 CSS 選擇器來選擇內容,並提取相關的文字和/或圖像以供使用。
在一個Parse方法中,我們也可以指定爬蟲希望繼續追蹤的超連結以及那些將被忽略的超連結。
我們可以使用 Scrape 方法提取任何資料,並將其轉儲為方便的 JSON 樣式文件格式,以便以後使用。
展望未來
要了解更多關於IronWebScraper的信息,我們建議您閱讀API參考文檔,然後開始查看我們文檔教學部分中的示例。
我們建議您查看的下一個示例是C#「部落格」網頁爬蟲示例,我們將學習如何從部落格(如WordPress部落格)中提取文本內容。 這在網站遷移中可能非常有用。
從這裡,您可以進一步查看其他進階網頁爬蟲教學示例,我們可以查看概念,如擁有多種類型頁面的網站,電子商務網站,以及如何在從互聯網抓取數據時使用多個代理、身份和登入。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。