【问题标题】:Jsoup selecting and replacing multiple <a> elementsJsoup 选择和替换多个 <a> 元素
【发布时间】:2012-02-23 16:50:01
【问题描述】:

所以我只是在尝试 Jsoup API 并有一个简单的问题。我有一个字符串,并且希望保持字符串完好无损,除非通过我的方法传递。我希望字符串通过此方法并取出包装链接的元素。现在我有:

public class jsTesting {
public static void main(String[] args) {
    String html = "<p>An <a href='http://example.com/'><b>example</b></a> link and after that is a second link called <a href='http://example2.com/'><b>example2</b></a></p>";
    Elements select = Jsoup.parse(html).select("a");
    String linkHref = select.attr("href");
    System.out.println(linkHref);       
}}

这只会返回第一个解包的 URL。我希望所有 URL 以及原始字符串都被解包。在此先感谢

编辑:解决方案:

非常感谢您的回答,我只是稍微编辑了它以获得我想要的结果。这是我正在使用的完整解决方案:

public class jsTesting {
public static void main(String[] args) {
    String html = "<p>An <a href='http://example.com/'><b>example</b></a> link and after that is a second link called <a href='http://example2.com/'><b>example2</b></a></p>";
    Document doc = Jsoup.parse(html);
    Elements links = doc.select("a[href]");
    for (Element link : links) {
        doc.select("a").unwrap();
    }
    System.out.println(doc.text());
}

}

再次感谢

【问题讨论】:

    标签: java parsing jsoup


    【解决方案1】:

    这是更正后的代码:

    public class jsTesting {
        public static void main(String[] args) {
            String html = "<p>An <a href='http://example.com/'><b>example</b></a> link and after that is a second link called <a href='http://example2.com/'><b>example2</b></a></p>";
            Elements links = Jsoup.parse(html).select("a[href]"); // a with href;
            for (Element link : links) {
                //Do whatever you want here
                System.out.println("Link Attr : " + link.attr("abs:href"));
                System.out.println("Link Text : " + link.text());    
            }       
        }
    }
    

    【讨论】:

    • 你最好使用link.absUrl("href"),而不是link.attr("abs:href")
    • 非常感谢,不胜感激。但是,有没有办法使用 unwrap() 方法来做到这一点?
    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    相关资源
    最近更新 更多