zoukankan      html  css  js  c++  java
  • 相对地址转化为绝对地址

    在博问中有朋友问起:如何将获取的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
  • 相关阅读:
    小程序升级实时音视频录制及播放能力,开放 Wi-Fi、NFC(HCE) 等硬件连接功能
    12306网站将新增微信通知方式
    QQ-AR助人教版小学英语“动”起来
    【福利】公众平台全面开放原创功能
    12月微信的新规来了
    微信公众平台原创声明和留言功能面向微信认证帐号公测
    微信公众平台支持开通微信小店小程序了
    腾讯2017年第三季度财报:微信广告收入大幅增长
    2017微信数据报告 截至9月日登录用户超9亿日发送消息380亿次
    iOS版微信6.5.21发布 适配iPhone X
  • 原文地址:https://www.cnblogs.com/downmoon/p/1594936.html
Copyright © 2011-2022 走看看