是的,假设我有这段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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句