URL相对地址转成绝对地址

 
三种方法替换相对地址为绝对地址
2006-10-18 00:36

1、<base>标签
当使用时,base 元素必须出现在文档的 head 内,在任何用于引用外部资源的元素之前。

此元素在 Internet Explorer 3.0 及以上版本的 HTML 中可用,在 Internet Explorer 4.0 及以上版本的脚本中可用。

此元素不改变内容的显示格式。

此元素不需要关闭标签。

<html>
  <head>
    <title>javascript change url</title>
    <BASE HREF="http://news.sina.com.cn/c/2006-10-17/155910257355s.shtml"/>
  </head>
  <body>
    <a href="/logo.gif">/logo.gif</a>
    <a href="../logo.gif">../logo.gif</a>
    <a href="logo.gif">logo.gif</a>
    <a href="http://www.sina.com.cn/">http://www.sina.com</a>
    <input type="button" value="click me" onClick="show()"/>
    <script language="javascript">
       function show() {
          var link = document.all.tags("a");
          for(var i=0;i<link.length;i++) {
             alert(link[i]);
         }
      }
   </script>
   </body>
</html>
 
2、Uri类
这个类可以通过定义baseurl和相对url的方式来生成新的url,这样就可以将网页中的相对地址转变为绝对地址。
代码示例:
Uri uri = new Uri("http://www.ita.doc.gov/td/industry/otea/trade-detail/");
Uri newuri = new Uri(uri,"Latest-December/Exports/index.html");
MessageBox.Show(newuri.AbsoluteUri);
Uri newuri2 = new Uri(newuri,"01/index.html");
MessageBox.Show(newuri2.AbsoluteUri);
Uri newuri3 = new Uri(newuri,"http://www.sina.com.cn");
MessageBox.Show(newuri3.AbsoluteUri);

可以用统一的方式来获得网页中链接的url。
Uri newuri = new Uri(baseuri,path);
baseuri是当前网页的url,path可以是相对地址,也可以是绝对地址。


3、正则表达式
    //for relative path
    string sURL = "http://www.microsoft.com/aaa/";
 s = Regex.Replace(s,
  @"<a\s+href\s*=\s*(['""])(?!http://|/)([^>]+)\1([^>]*)>",
  "<a href=$1" + sURL + "$2$1$3>",
 RegexOptions.Singleline | RegexOptions.IgnoreCase);

 //for absolute path
 sURL = "http://www.microsoft.com/";
 s = Regex.Replace(s,
  @"<a\s+href\s*=\s*(['""])(?!http://)/([^>]+)\1([^>]*)>",
  "<a href=$1" + sURL + "$2$1$3>",
 RegexOptions.Singleline | RegexOptions.IgnoreCase);


最近在做个HTMLParser抓取网页内容;
有些网页的链接写的都是相对路径;
在CSDN上找到的,记录一下。

Java代码
  1. @SuppressWarnings("finally")   
  2. public static String getAbsoluteURL(String baseURI, String relativePath){   
  3.     String abURL=null;   
  4.     try {   
  5.         URI base=new URI(baseURI);//基本网页URI    
  6.         URI abs=base.resolve(relativePath);//解析于上述网页的相对URL,得到绝对URI    
  7.         URL absURL=abs.toURL();//转成URL    
  8.         System.out.println(absURL);   
  9.         abURL = absURL.toString();   
  10.     } catch (MalformedURLException e) {   
  11.         e.printStackTrace();   
  12.     } catch (URISyntaxException e) {   
  13.         e.printStackTrace();   
  14.     } finally{   
  15.         return abURL;   
  16.     }   
  17. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值