如何让 Jsoup 白名单接受某些属性内容

Posted

技术标签:

【中文标题】如何让 Jsoup 白名单接受某些属性内容【英文标题】:How to make a Jsoup whitelist to accept certain attribute content 【发布时间】:2014-04-22 01:20:03 【问题描述】:

我正在使用带有宽松白名单的 Jsoup。看起来很完美,但我想保留嵌入的图像标签,如<img alt="" src="data:;base64

有没有办法修改白名单以接受那些img?

编辑

如果我使用Whitelist.relaxed().addProtocols("img","src","data"),则不会删除这些 img 标签。但它接受“data:”之后的任何内容,如果 src 内容以“data:;base64”开头,我只想保留它们。用jsoup可以吗?

【问题讨论】:

对我来说,我什至不必将它列入白名单来保留它。一些更多的源 html 可能和你的解析代码一样好。 Daniel:我正在使用 jsoup 1.7.2 和 Jsoup.clean(..., Whitelist.relaxed()。上述格式的任何类型的 img 都会被删除。 【参考方案1】:

您可以扩展白名单并覆盖 isSafeAttribute 以执行自定义检查。由于无法直接扩展 Whitelist.relaxed(),您必须复制一些代码来设置相同的列表:

public class RelaxedPlusDataBase64Images extends Whitelist 
    public RelaxedPlusDataBase64Images() 
        //copied from Whitelist.relaxed()
        addTags("a", "b", "blockquote", "br", "caption", "cite", "code", "col",
                "colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6",
                "i", "img", "li", "ol", "p", "pre", "q", "small", "strike", "strong",
                "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u",
                "ul");
        addAttributes("a", "href", "title");
        addAttributes("blockquote", "cite");
        addAttributes("col", "span", "width");
        addAttributes("colgroup", "span", "width");
        addAttributes("img", "align", "alt", "height", "src", "title", "width");
        addAttributes("ol", "start", "type");
        addAttributes("q", "cite");
        addAttributes("table", "summary", "width");
        addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width");
        addAttributes("th", "abbr", "axis", "colspan", "rowspan", "scope", "width");
        addAttributes("ul", "type");
        addProtocols("a", "href", "ftp", "http", "https", "mailto");
        addProtocols("blockquote", "cite", "http", "https");
        addProtocols("cite", "cite", "http", "https");
        addProtocols("img", "src", "http", "https");
        addProtocols("q", "cite", "http", "https");
    

    @Override
    protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) 
        return ("img".equals(tagName)
                && "src".equals(attr.getKey())
                && attr.getValue().startsWith("data:;base64")) ||
            super.isSafeAttribute(tagName, el, attr);
    

由于您没有提供用于解析的代码或您正在清理的 HTML,因此我没有对此进行测试。

【讨论】:

以上是关于如何让 Jsoup 白名单接受某些属性内容的主要内容,如果未能解决你的问题,请参考以下文章

为啥白名单不会出现错误模型 NestJs 的错误

如何设置urlfilter的白名单?

微信公众号如何查看转载白名单

UAC白名单有没有用?

使用UAC白名单让指定的程序不受UAC限制,很实用的哦

白名单是啥意思?