本文介紹網絡蜘蛛獲取網頁中所有鏈接的方法,實現原理:使用system.net.webclient類獲取遠程網頁內容,然后使用url正則表達式分析html代碼中的鏈接。代碼如下:
using system;
using system.net;
using system.text;
using system.text.regularexpressions;
namespace httpget
{
class class1
{
[stathread]
static void main(string[] args)
{
system.net.webclient client = new webclient();
byte[] page = client.downloaddata("http://news.163.com");
string content = system.text.encoding.utf8.getstring(page);
string regex = "href=[///"http:///'](http://////|//.///|///)?//w+(//.//w+)*(/////w+(//.//w+)?)*(///|//?//w*=//w*(&//w*=//w*)*)?[///"http:///']";
regex re = new regex(regex);
matchcollection matches = re.matches(content);
system.collections.ienumerator enu = matches.getenumerator();
while (enu.movenext() && enu.current != null)
{
match match = (match)(enu.current);
console.write(match.value + "/r/n");
}
}
}
}
新聞熱點
疑難解答