min*_*das 1 html java xss jsoup htmlcleaner
我正在评估jsoup的功能,它将清理(但不删除!)非白名单标签.假设只<b>允许标记,所以输入如下
foo <b>bar</b> <script onLoad='stealYourCookies();'>baz</script>
Run Code Online (Sandbox Code Playgroud)
必须产生以下结果:
foo <b>bar</b> <script onLoad='stealYourCookies();'>baz</script>
Run Code Online (Sandbox Code Playgroud)
我用jsoup看到以下问题/问题:
document.getAllElements()总是假设<html>,<head>和<body>.是的,我可以打电话,document.body().getAllElements()但关键是我不知道我的源文件是完整的HTML文档还是仅仅是正文 - 我希望结果的形状和形式与它相同;<script>...</script>使用<script>...</script>?我只想用转义实体替换括号,并且不想改变任何属性,等等.Node.replaceWith听起来像是一种矫枉过正.或者我应该使用另一个框架?到目前为止,我已经浏览了htmlcleaner,但是给出的示例并未建议我支持所需的功能.
你如何Document使用Jsoup 加载/解析你的?如果您使用parse()或connect().get()jsoup将会被自动格式化你的HTML(插入html,body和head标签).这样可以确保您始终拥有完整的Html文档 - 即使输入不完整.
假设您只想清理输入(无需处理),而应使用clean()之前列出的方法.
示例1 - 使用parse()
final String html = "<b>a</b>";
System.out.println(Jsoup.parse(html));
Run Code Online (Sandbox Code Playgroud)
输出:
<html>
<head></head>
<body>
<b>a</b>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
输入html已完成,以确保您拥有完整的文档.
示例2 - 使用clean()
final String html = "<b>a</b>";
System.out.println(Jsoup.clean("<b>a</b>", Whitelist.relaxed()));
Run Code Online (Sandbox Code Playgroud)
输出:
<b>a</b>
Run Code Online (Sandbox Code Playgroud)
输入html被清理,而不是更多.
文档:
该方法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);
Run Code Online (Sandbox Code Playgroud)
输出:
<html>
<head></head>
<body>
<b><script>your script here</script></b>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
或仅限身体:
System.out.println(doc.body().html());
Run Code Online (Sandbox Code Playgroud)
输出:
<b><script>your script here</script></b>
Run Code Online (Sandbox Code Playgroud)
文档:
是的,这样做的prettyPrint()方法Jsoup.OutputSettings.
例:
final String html = "<p>your html here</p>";
Document doc = Jsoup.parse(html);
doc.outputSettings().prettyPrint(false);
System.out.println(doc);
Run Code Online (Sandbox Code Playgroud)
注意:如果outputSettings()方法不可用,请更新Jsoup.
输出:
<html><head></head><body><p>your html here</p></body></html>
Run Code Online (Sandbox Code Playgroud)
文档:
没有!Jsoup是最好的,最有能力的 Html库之一!
| 归档时间: |
|
| 查看次数: |
3068 次 |
| 最近记录: |