分享

9. Working with URLs

 goldbomb 2010-10-08

Working with URLs

Problem

You have a HTML document that contains relative URLs, which you need to resolve to absolute URLs.

Solution

  1. Make sure you specify a base URI when parsing the document (which is implicit when loading from a URL), and
  2. Use the abs: attribute prefix to resolve an absolute URL from an attribute:
Document doc = Jsoup.connect("http://").get(); 
Element link = doc.select("a").first(); 
String relHref = link.attr("href"); // == "/" 
String absHref = link.attr("abs:href"); // "http:///"

Description

In HTML elements, URLs are often written relative to the document's location: <a href="/download">...</a>. When you use the Node.attr(String key) method to get a href attribute, it will be returned as it is specified in the source HTML.

If you want to get an absolute URL, there is a attribute key prefix abs: that will cause the attribute value to be resolved against the document's base URI (original location): attr("abs:href")

For this use case, it is important to specify the base URI when parsing the document.

If you don't want to use the abs: prefix, there is also a method Node.absUrl(String key) which does the same thing, but accesses via the natural attribute key.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多