繁体   English   中英

使用jsoup逃避不允许的标签

[英]Using jsoup to escape disallowed tags

我正在评估jsoup的功能,该功能可以清理(但不能删除!)未列入白名单的标签。 假设仅允许使用<b>标记,因此以下输入

foo <b>bar</b> <script onLoad='stealYourCookies();'>baz</script>

必须产生以下内容:

foo <b>bar</b> &lt;script onLoad='stealYourCookies();'&gt;baz&lt;/script&gt;

我发现jsoup存在以下问题/问题:

  • document.getAllElements()始终采用<html><head><body> 是的,我可以调用document.body().getAllElements()但要点是我不知道我的源文件是完整的HTML文档还是仅仅是正文-我希望结果的形状和形式与它进来了;
  • 如何将<script>...</script>替换为&lt;script&gt;...&lt;/script&gt; 我只想用转义的实体替换方括号,并且不想更改任何属性,等等Node.replaceWith听起来对此Node.replaceWith大材小用。
  • 是否可以完全关闭漂亮的打印(例如插入新行等)?

也许我应该使用其他框架? 到目前为止,我已经窥视了htmlcleaner ,但是给出的示例并不表明支持我所需的功能。

答案1

如何使用Jsoup加载/解析Document 如果使用parse()connect().get() jsoup将自动格式化html(插入htmlbodyhead标签)。 这样可以确保您始终拥有完整的HTML文档-即使输入不完整。

假设您只想清除输入(无需进一步处理),则应使用clean()而不是前面列出的方法。

示例1-使用parse()

final String html = "<b>a</b>";

System.out.println(Jsoup.parse(html));

输出:

<html>
 <head></head>
 <body>
  <b>a</b>
 </body>
</html>

输入html已完成,以确保您具有完整的文档。

示例2-使用clean()

final String html = "<b>a</b>";

System.out.println(Jsoup.clean("<b>a</b>", Whitelist.relaxed()));

输出:

<b>a</b>

输入html被清除,不能更多。

说明文件:


答案2

方法replaceWith()完全满足您的需求:

例:

final String html = "<b><script>your script here</script></b>";
Document doc = Jsoup.parse(html);

for( Element element : doc.select("script") )
{
    element.replaceWith(TextNode.createFromEncoded(element.toString(), null));
}

System.out.println(doc);

输出:

<html>
 <head></head>
 <body>
  <b>&lt;script&gt;your script here&lt;/script&gt;</b>
 </body>
</html>

仅身体

System.out.println(doc.body().html());

输出:

<b>&lt;script&gt;your script here&lt;/script&gt;</b>

说明文件:


答案3

是的, Jsoup.OutputSettings prettyPrint()方法Jsoup.OutputSettings做到这一点。

例:

final String html = "<p>your html here</p>";

Document doc = Jsoup.parse(html);
doc.outputSettings().prettyPrint(false);

System.out.println(doc);

注意:如果outputSettings()方法不可用,请更新Jsoup。

输出:

<html><head></head><body><p>your html here</p></body></html>

说明文件:


答案4 (无项目符号)

没有! Jsoup是那里最好 ,功能最强大的 HTML库之一!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM