如何使用Jsoup从相对HTML链接中提取绝对URL? [英] How to extract absolute URL from relative HTML links using Jsoup?
本文介绍了如何使用Jsoup从相对HTML链接中提取绝对URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Jsoup 来提取网页的网址。这些网址的 href
属性是相对的:
I am using Jsoup to extract URL of an webpage. The href
attribute of those URL's are relative like:
<a href="/text">example</a>
这是我的尝试:
Document document = Jsoup.connect(url).get();
Elements results = document.select("div.results");
Elements dls = results.select("dl");
for (Element dl : dls) {
String url = dl.select("a").attr("href");
}
这样可行,但如果我使用
This works fine, but if I use
String url = dl.select("a").attr("abs:href");
获取绝对网址,例如 http://example.com/text
,它不起作用。如何获得绝对URL?
to get the absolute URL like http://example.com/text
, it is not working. How can I get the absolute URL?
推荐答案
您需要 元素#absUrl()
。
String url = dl.select("a").absUrl("href");
您可以顺便缩短选择范围:
You can by the way shorten the select:
Document document = Jsoup.connect(url).get();
Elements links = document.select("div.results dl a");
for (Element link : links) {
String url = link.absUrl("href");
}
这篇关于如何使用Jsoup从相对HTML链接中提取绝对URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文