利用URL

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://jsoup.org").get();

Element link = doc.select("a").first();
String relHref = link.attr("href"); // == "/"
String absHref = link.attr("abs:href"); // "http://jsoup.org/"

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.


转载于:https://my.oschina.net/u/553266/blog/296066

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值