您的位置:首页 > 编程语言

得到一个网页的所有herf 链接代码

2006-10-26 12:55 543 查看
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;

1.先取得网页的原代码

Uri url=new Uri("http://www.blogjava.net/wujun");
HttpWebRequest request=(HttpWebRequest) WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
string str=sr.ReadToEnd();
sr.Close();
stream.Close();
response.Close();

得到网页的html源代码以后。再根据源代码分析 所有 <a href ="url"> 最后得到 href后面 url的链接地址

正则表达式

Regex RegExFindHref = new Regex(@"<a/s+([^>]*/s*)?href/s*=/s*(?:""(?<1>[//a-z0-9_][^""]*)""|'(?<1>[//a-z0-9_][^']*)'
|(?<1>[//a-z0-9_]/S*))(/s[^>]*)?>(?<2>.*?)</a>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);

循环读出 连接地址

for (Match m = RegExFindHref.Match(str); m.Success; m = m.NextMatch())
{
TextBox1.Text+= m.Groups[1].ToString()+"/n";

}

运行后
TextBox1 将显示分析后的所有网页的连接 :
http://www.dotlucene.net/ http://www.castleproject.org/ http://www.codeplex.com/ http://www.codeproject.com/ http://www.asp.net/ http://www.nhibernate.org/ http://www.blogjava.net/wujun/CommentsRSS.aspx http://www.blogjava.net/wujun/archive/2006/10/23/47150.html#76745 http://www.blogjava.net/wujun/archive/2006/10/23.html http://www.blogjava.net/wujun/archive/2006/10/23/76769.html http://www.blogjava.net/wujun/archive/2006/10/23/76769.html http://www.blogjava.net/wujun/archive/2006/10/23/76769.html#FeedBack http://www.blogjava.net/wujun/admin/EditPosts.aspx?postid=76769 http://www.blogjava.net/wujun/AddToFavorite.aspx?id=76769 http://www.blogjava.net/wujun/archive/2006/10/20.html ......
..............
.........................等等等。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐