blogjava's web log

blogjava's web log
...

【小技巧】如何得到一个网页的所有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();

得到网页的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
 ......
..............
 .........................等等等。。。



刚刚看到一个JAVA版。
地址:  http://www.blogjava.net/ekinglong/archive/2006/10/27/77688.html


posted on 2006-10-26 12:46 record java and net 阅读(1821) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

常用链接

留言簿(44)

新闻档案

2.动态语言

3.工具箱

9.文档教程

友情链接

搜索

最新评论