java - 将相对路径转换为绝对路径在 JSoup 中不起作用

标签 java html jsoup

我正在尝试访问网页中的相对链接(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/

相关文章:

java - Android Java JSoup 搜索然后检索结果

Java/Android 如何从 html 响应中获取 JSON?

java - JSON <=> Java 对象映射器,可与 J2objc 很好地转换

java - 动态改变文本框JTextArea的大小

javascript - 如果用户使用带有 anchor /哈希的链接访问网站,我如何将样式应用于元素

javascript - HTML/JavaScript/Textarea - 如何找到调整大小的文本区域的行值

java - jsoup 从 header 检索特定表

java - 二维数组排序

java - java中是否需要添加 volatile 关键字来保证单例类的线程安全?

html - 让搜索引擎知道原图