Jsoup 添加 JS 脚本内容时出现的转义问题
使用 Jsoup 添加一个元素时, 如果设置文本内容则会将对应的 “<”,"&“等字符转义为 html 的字符 “< ;” ,“& ;”。如果添加的是 JS 脚本则要避免这些字符的转移。使用 “appendChild(DataNode dataNode)” 的方法即可。如下示例所示:
使用 text(String text) 方法添加 JS 脚本:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class Application {
public static void main(String[] args) {
Document document = Jsoup.parse("<!DOCTYPE HTML>\n" +
"<html>\n" +
"\t<head>\n" +
"\t\t<title>Hello World!</title>\n" +
"\t</head>\n" +
"\t<body>\n" +
"\t</body>\n" +
"</html>");
document.selectFirst("body")
.appendElement("script")
.attr("type", "text/javascript")
.text("""
let i;
for (i = 0; i < elementList.length; ++i) {
i++;
}""");
System.out.println(document.html());
}
}
可以看到, 使用 text() 方法添加的内容将会对字符进行转义。

使用 appendChild(DataNode dataNode) 添加 JS 脚本
import org.jsoup.Jsoup;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
public class Application {
public static void main(String[] args) {
Document document = Jsoup.parse("<!DOCTYPE HTML>\n" +
"<html>\n" +
"\t<head>\n" +
"\t\t<title>Hello World!</title>\n" +
"\t</head>\n" +
"\t<body>\n" +
"\t</body>\n" +
"</html>");
document.selectFirst("body")
.appendElement("script")
.attr("type", "text/javascript")
.appendChild(new DataNode("""
let i;
for (i = 0; i < elementList.length; ++i) {
i++;
}"""));
System.out.println(document.html());
}
}
结果如下:

可以看到, 这里添加的 JS 脚本并没有对 “<” 进行转义。
本文介绍了在使用Jsoup解析HTML时,如何避免JS脚本内容被自动转义的问题。通过示例代码展示了使用`text(String text)`方法会将特殊字符转义,而使用`appendChild(DataNode dataNode)`方法可以正确添加不被转义的JS脚本。对于需要插入JS脚本的场景,推荐使用后者。
431

被折叠的 条评论
为什么被折叠?



