日期:2014-04-15  浏览次数:20377 次

输入一个地址,就可以把那个网页中的链接提取出来,下面这段代码可以轻松实现,主要的是用到了正则表达式。
  
  GetUrl.ASPx代码如下:
  
  <%@ Page Language="<a href="http://dev.21tx.com/language/vb/" target="_blank">VB</a>" CodeBehind="GetUrl.aspx.vb" AutoEventWireup="false" Inherits="aspx<a href="http://dev.21tx.com/web/" target="_blank">Web</a>.GetUrl" %>
  <html>
  <head>
  <META http-equiv="content-type" content="text/html; charset=gb2312">
  </head>
  <body>
  <form id="Form1" method="post" runat="server">
   <P>
   <asp:Label id="Label1" runat="server"></asp:Label>
   <asp:TextBox id="urlTextBox" runat="server" Width="336px">
   http://lucky_elove.www1.dotnetplayground.com/
   </asp:TextBox>
   <asp:Button id="scrapeButton" runat="server"></asp:Button>
   </P>
   <HR width="100%" SIZE="1">
   <P>
   <asp:Label id="TipResult" runat="server"></asp:Label>
   <asp:TextBox id="resultLabel" runat="server" TextMode="MultiLine"
   Width="100%" Height="400"></asp:TextBox>
   </P>
  </form>
  </body>
  </html>
  后代码GetUrl.aspx.vb如下:
  
  Imports System.IO
  Imports System.Net
  Imports System.Text
  Imports System.Text.RegularExpressions
  Imports System
  
  Public Class GetUrl
   Inherits System.Web.UI.Page
   Protected WithEvents Label1 As System.Web.UI.WebControls.Label
   Protected WithEvents urlTextBox As System.Web.UI.WebControls.TextBox
   Protected WithEvents scrapeButton As System.Web.UI.WebControls.Button
   Protected WithEvents TipResult As System.Web.UI.WebControls.Label
   Protected WithEvents resultLabel As System.Web.UI.WebControls.TextBox
  
  #Region " Web 窗体设计器生成的代码 "
  
   '该调用是 Web 窗体设计器所必需的。
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  
   End Sub
  
   Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
   'CODEGEN: 此方法调用是 Web 窗体设计器所必需的
   '不要使用代码编辑器修改它。
   InitializeComponent()
   End Sub
  
  #End Region
  
   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   '在此处放置初始化页的用户代码
   Label1.Text = "请输入一个URL地址:"
   scrapeButton.Text = "分离Href链接"
   End Sub
   Private report As New StringBuilder()
   Private webPage As String
   Private countOfMatches As Int32
  
   Public Sub scrapeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
   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 As String = linksExpression.Replace(webPage,