只要輸入一個網址,就能把該網頁裡的所有連結提取出來,這件事用一段簡單的程式就能做到,關鍵在於善用正則表達式(Regular Expression)。
畫面上放一個文字框讓使用者輸入 URL、一顆按鈕觸發抓取,再用多行文字框顯示結果:
form id="Form1" method="post" runat="server"
asp:TextBox id="urlTextBox" runat="server" Width="336px"/
asp:Button OnClick="scrapeButton_Click" id="scrapeButton" runat="server"/
asp:TextBox id="resultLabel" runat="server" TextMode="MultiLine" Width="100%" Height="400"/
/form
先引入需要的命名空間:
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions
抓取網頁的動作由 GrabUrl 完成,接著用 Regex 比對出所有 a 標籤的 href:
webPage = GrabUrl()
Dim myDelegate As New MatchEvaluator(AddressOf MatchHandler)
Dim linksExpression As New Regex( _
"<a.+?href=['""](?!http)(?!mailto:)(?<foundAnchor[^'""]+?)[""']", _
RegexOptions.Multiline Or RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)
Dim newWebPage = linksExpression.Replace(webPage, myDelegate)
其中 (?!http)、(?!mailto:) 是「否定式先行預查」,用來排除外部連結與 mailto;命名群組 foundAnchor 則用來把比對到的網址取出。MatchHandler 負責處理每一個比對結果,統計筆數並整理成清單。
整個流程就是:抓取原始 HTML → 用正則表達式找出所有 a 的 href → 過濾掉不需要的類型 → 輸出整理後的清單。正則表達式在這裡扮演了靈活的「解析器」角色,理解它的語法後,類似的網頁資料擷取都能如法炮製。