【小技巧】如何得到一个网页的所有a标记 herf 链接代码
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();
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);
|(?<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.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
......
..............
.........................等等等。。。
posted on 2006-10-26 12:50 hello csharp 阅读(1448) 评论(4) 编辑 收藏 举报