相对地址转化为绝对地址

在博问中有朋友问起:如何将获取的html代码中的相对地址转化为绝对地址?

http://space.cnblogs.com/question/9655/ 

稍做小结,以方便更多的朋友查询。

基本思路:

1、先用正则得到所有的页面源码中所有的url,

可以参考这个

(?<=href\s*=)(?:[ \s""']*)(?!#|mailto|location.|javascript|.*css|.*this\.)[^""']*(?:[ \s>""'])

 得到的值可能如下:

"/company/list.aspx"
"http://www.sohu.com/index.html"
..

2、然后再拼接加上前缀这个前缀就是你的页面的根目录,之前就已经知道的。

大概写了个简单例子:获取页面内容部分省略了·! 网上资源很多。
也可以看这里

http://www.cnblogs.com/downmoon/archive/2009/07/01/1514519.html
public static void Main(string[] args)
        {
            
string minHtml = string.Empty;
            
string url = @"http://www.agronet.com.cn/default.aspx";
            
string preurl = url.Remove(url.IndexOf('/'8+ 1);//获取url的根目录地址
            minHtml = GetRequestString(url, 60001, System.Text.Encoding.UTF8);//获取指定页面的内容
            Console.WriteLine(preurl);
            GetUrlListBHtml(minHtml,preurl);
            Console.ReadKey();
        }
        
/// <summary>
        
/// 获取html内容中的相对url地址,并向相对地址添加前缀
        
/// </summary>
        
/// <param name="text">html内容</param>
        
/// <param name="pre">要添加的绝对地址前缀</param>
        public static void GetUrlListBHtml(string text,string pre)
        {
            
string pat = @"(?<=href\s*=)(?:[ \s""']*)(?!#|mailto|location.|javascript|.*css|.*this\.)[^""']*(?:[ \s>""'])";
            
// Compile the regular expression.
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(pat, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            
// Match the regular expression pattern against a text string.
            System.Text.RegularExpressions.Match m = r.Match(text);
            
int matchCount = 0;
            
while (m.Success)
            {
                
string urlX=m.Value.Replace("\"","");//替换引号
                if (urlX.IndexOf("/"== 0)//相对地址
                {
                    matchCount
++;
                    Console.WriteLine(
"" + matchCount+"个相对地址:");
                    Console.WriteLine(
"原地址是"+urlX);
                    Console.WriteLine(
"新的绝对地址是" + pre+urlX);
                    Console.WriteLine(
"------------------------------------");
                }
                m 
= m.NextMatch();
            }
        }
邀月注:本文版权由邀月和博客园共同所有,转载请注明出处。
助人等于自助!  3w@live.cn
原文地址:https://www.cnblogs.com/downmoon/p/1594936.html