【问题标题】:Jsoup is removing the href attribute with a placeholder valueJsoup 正在使用占位符值删除 href 属性
【发布时间】:2016-03-02 01:15:57
【问题描述】:

我正在使用jsoup 清理一些 html。 我正在使用Whitelist.relaxed() 进行清洁。这在大多数情况下效果很好,我想继续使用它。

问题是我有一个占位符 href 值,清理正在删除。

例如,<a href="{placeholder}">text</a>。这将更改为<a>text</a>。有没有办法用我的place holder 值保留href attribute

提前致谢

【问题讨论】:

  • 你看过addAttributes白名单选项了吗?
  • 我有。我创建了以下白名单: private static final Whitelist WHITELIST = Whitelist.relaxed().preserveRelativeLinks(true) .addTags("span") .addTags("hr") .addAttributes(":all", "style") 。 addAttributes(":all", "id") .addAttributes(":all", "target") .addProtocols("a", "href", "{");我已经玩了一点,但没有运气

标签: jsoup


【解决方案1】:

我猜您没有为clean 方法提供有效的基本URI。如果你这样做,那么你可以保留hrefs。如果您还使用白名单指定preserveRelativeLinks(true),则链接也可以是相对的。

所以在清洁时做这样的事情:

String html = "<a href=\"{placeholder}\">text</a>";
String cleaned = Jsoup.clean(html, 
                             "http://base.uri",
                             Whitelist.relaxed().preserveRelativeLinks(true));
System.out.println(cleaned);

这将导致以下输出:

<a href="{placeholder}">text</a>

【讨论】:

    【解决方案2】:

    如果你只有 href 属性,你可以使用 "preserveRelativeLinks(true)" 。但是您已经有了 target = "_blank" 或不同的属性,方法可以在一个 url 中查看所有这些属性。所以我更喜欢 WhiteList 的“addAttributes(String tag, String... attributes)”WhiteList addAttributes

    这样的代码:

    WhiteList whiteList = WhiteList.none();
    whitelist.addAttributes("a","href","target");
    whitelist.addAttributes("img","src");
    
    String cleanText = Jsoup.clean(htmlText, whitelist);
    

    【讨论】:

      猜你喜欢
      • 2022-08-08
      • 2013-06-27
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多