我正在尝试访问网页中的相对链接(a[href])并将其替换为绝对链接,并在控制台上打印修改后的网页 HTML。但是,当我运行程序后查看链接时,没有进行任何更改。这是我的代码:
Document doc = null;
try {
doc = Jsoup.connect("http://jsoup.org/cookbook/extracting-data/dom-navigation").userAgent("Mozilla").get();
} catch (IOException e1) {
e1.printStackTrace();
}
Elements imports = doc.select("a[href]");
String s = "";
for (Element link : imports) {
//System.out.println("\n"+link.attr("href"));
//System.out.println(link.attr("abs:href"));
if(link.attr("href").equalsIgnoreCase("/")){
//Do nothing for now
}
else{
s = doc.toString().replaceAll(link.attr("href"), link.attr("abs:href"));
}
}
System.out.println(s);
一件非常奇怪的事情是,在这个程序中,我连接到 http://jsoup.org/cookbook/extracting-data/dom-navigation但是当我连接到此链接http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html时我注意到正在做出改变。那么这里可能有什么问题,我的代码或网页有问题吗?!
最佳答案
请尝试<your element>.absUrl("href")
反而。为了进行测试,请在更改后元素直接打印结果。
要替换网址,您可以使用类似的内容(未测试):
Elements urls = doc.select("a[href]");
for( Element urlElement : urls )
{
urlElement.attr("href", urlElement.absUrl("href"));
System.out.println(urlElement); // Print result directly after changes have been done
}
关于java - 将相对路径转换为绝对路径在 JSoup 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22307023/