输入一个地址,就可以把那个网页中的链接提取出来,下面这段代码可以轻松实现,主要的是用到了正则表达式。
geturl.aspx代码如下:
后代码geturl.aspx.vb如下:
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 窗体设计器所必需的。
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( _
“\
regexoptions.multiline or regexoptions.ignorecase or regexoptions.ignorepatternwhitespace)
dim newwebpage as string = linksexpression.replace(webpage, mydelegate)
tipresult.text = “
从 ” & urltextbox.text & “分离出的href链接
” & _
“找到并整理” & countofmatches.tostring() & ” 个链接
” & _
report.tostring().replace(environment.newline, “
“)
tipresult.text &= “
整理过的页面
”
resultlabel.text = newwebpage
end sub
public function matchhandler(byval m as match) as string
dim link as string = m.groups(“foundanchor”).value
dim rtol as new regex(“^”, regexoptions.multiline or regexoptions.righttoleft)
dim col, row as int32
dim linebegin as int32 = rtol.match(webpage, m.index).index
row = rtol.matches(webpage, m.index).count
col = m.index – linebegin
report.appendformat( _
“link {0}, fixed at row: {1}, col: {2}{3}”, _
server.htmlencode(m.groups(0).value), _
row, _
col, _
environment.newline _
)
dim newlink as string
if link.startswith(“/”) then
newlink = link.substring(1)
else
newlink = link
end if
countofmatches += 1
return m.groups(0).value.replace(link, newlink)
end function
private function graburl() as string
dim wc as new webclient()
dim s as stream = wc.openread(urltextbox.text)
dim sr as streamreader = new streamreader(s, system.text.encoding.default)
graburl = sr.readtoend
s.close()
wc.dispose()
end function
end class