所以是的,假设我有这段 HTML
<p>And finally, how about some <a href="http://www.yahoo.com/">Links?</a></p>
我只想访问和修改“最后,一些怎么样”部分,并得到这个:
<p>new text <a href="http://www.yahoo.com/">Links?</a></p>
我似乎不知道该怎么做。这是我到目前为止所尝试过的:
Document doc = null;
try {
doc = Jsoup.connect("http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html").userAgent("Mozilla").get();
} catch (IOException e1) {
e1.printStackTrace();
}
Elements d = doc.body().children();
Element e = d.get(20); //Assuming the HTML line in question is found at index 20
e.text("new text") //just outputs <p>new value</p>, which is not good for me
看来我可以通过以下方式访问它
Element e = d.get(20);
System.out.println("\n"+e.ownText()); //outputs: And finally, how about some
但是修改它不起作用。
Element e = d.get(20);
String s = e.toString().replace(e.ownText(), "new text");
e.text(s);
System.out.println(e.toString());
上面代码的输出是
<p><p>changed <a href="http://www.yahoo.com/">Links?</a></p></p>
它似乎将标签视为文字,但我希望它们为 < 或 >,因为然后我必须使用新文本重新构建网页。
我们将非常感谢任何形式的帮助。
最佳答案
像这样的东西怎么样
Element e = d.get(20);
e.text("new text");
e.append("<a href=\"http://www.yahoo.com/\">Links?</a>");//lets you add HTML.
如果链接是动态的并且您不想更改它,您可以提前存储它并稍后使用
Element e = d.get(20);
Element link = e.child(0);
e.text("new text");
e.append(link.toString());
关于java - 使用 JSoup 在 Java 中修改 html 标签自己的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22205683/