如何在jsoup中更改元素的文本?

问题描述 投票:1回答:1

我正在遍历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>
java html jsoup
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.