[英]Modifying an html tag's own text in Java using JSoup
是的,假設我有這段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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.