我有几个 HTMLS,我想在其中找到特定的 div 并用新的代码行更新它们。
目前,我在我的 JAVA 后端中使用 Jsoup 作为 HTML 解析器,但不知何故它没有更新所需的内容而是从现有的 HTML 中删除脚本和其他部分。
这是我正在使用的代码。
File file = new File("C:/2015/05 May/sample.html");
Document doc = Jsoup.parse(file, "UTF-8");
// clear the <head> element and add a new <script> element.
doc.head().appendElement("script")
.attr("type", "text/javascript")
.attr("src", "newScriptToAddInHeaderSection.js");
for( Element element : doc.select("div.sampleDiv") )
{
element.remove();
System.out.println("REMOVED..");
}
//write the changed HTML to the same file.
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(doc.html());
在执行这段代码时。它将在标题部分添加新的 JS 文件。然后,它从我的 HTML 中删除“sampleDiv”以及其他脚本和 div。 我只需要用新内容更新这个“sampleDiv”。
请帮忙!!
最佳答案
It is removing "sampleDiv" but also other scripts and divs from my HTML.
element.remove();
将从 HTML 树中删除 sampleDiv 及其所有子节点。这可以解释为什么其他脚本和 div 也被删除。
I only need to update this "sampleDiv" with new Content.
你能明确说明这个“sampleDiv”实际上是什么吗?
关于java - 如何在 JAVA 中用新代码更新 HTML Header 和指定的 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30621301/