我正在遍历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>
您正在使用.select("*")
选择文档中的所有元素,结果是您也替换了<body>
的内容,因此所有其他内容都会丢失。尝试通过选择元素来更具体。