【发布时间】:2020-09-18 09:54:28
【问题描述】:
我正在遍历 HTML 文档并更改元素的文本,但 Jsoup 在尝试更改任何元素的文本时不起作用。我的代码是:
// URL
String url = "http://example.com/source.html";
Document doc = Jsoup.connect(url)
.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
.referrer("http://www.google.com")
.ignoreHttpErrors(true).get();
// Select all of the elements in the HTML
Elements eles = doc.body().select("*");
// For each element
for (Element ele : eles) {
String text = ele.ownText();
System.out.println(text);
ele.text("newText");
}
File htmlFile = new File("output.html");
PrintWriter pw = new PrintWriter(htmlFile, "UTF-8");
// Write our translated HTML to the output file
pw.println(doc);
pw.close();
我得到的 HTML 正文是:
<body>
newText
</body>
【问题讨论】: