jsoup - 设置HTML

jsoup - 设置HTML 首页 / JSoup入门教程 / jsoup - 设置HTML

以下示例将HTML解析为Document对象之后,使用html,append,prepend()方法将值写入指定位置。

Document document=Jsoup.parse(html);
Element div=document.getElementById("sampleDiv");     
div.html("<p>This is a sample content.</p>");   
div.prepend("<p>Initial Text</p>");
div.append("<p>End Text</p>");   

元素对象代表dom元素,并提供各种方法来将html设置,添加或添加到dom元素。

append/prepend/html示例

使用您选择的任何编辑器在C:/> jsoup中创建以下Java程序。

JsoupTester.java

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class JsoupTester {
   public static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<div id='sampleDiv'><a id='googleA' href='www.google.com'>Google</a></div>"
         +"</body></html>";
      Document document = Jsoup.parse(html);

      Element div = document.getElementById("sampleDiv");
      System.out.println("Outer HTML Before Modification :\n"  + div.outerHtml());
      div.html("<p>This is a sample content.</p>");
      System.out.println("Outer HTML After Modification :\n"  + div.outerHtml());
      div.prepend("<p>Initial Text</p>");
      System.out.println("After Prepend :\n"  + div.outerHtml());
      div.append("<p>End Text</p>");
      System.out.println("After Append :\n"  + div.outerHtml());          
   }
}

使用 javac 编译器编译类,如下所示:

C:\jsoup>javac JsoupTester.java

现在运行JsoupTester以查看输出。

链接:https://www.learnfk.comhttps://www.learnfk.com/jsoup/jsoup-set-html.html

来源:LearnFk无涯教程网

C:\jsoup>java JsoupTester

查看输出。

无涯教程网

Outer HTML Before Modification :
<div id="sampleDiv">
 <a id="googleA" href="www.google.com">Google</a>
</div>
Outer HTML After Modification :
<div id="sampleDiv">
 <p>This is a sample content.</p>
</div>
After Prepend :
<div id="sampleDiv">
 <p>Initial Text</p>
 <p>This is a sample content.</p>
</div>
After Append :
<div id="sampleDiv">
 <p>Initial Text</p>
 <p>This is a sample content.</p>
 <p>End Text</p>
</div>
Outer HTML Before Modification :
<span>Sample Content</span>
Outer HTML After Modification :
<span>Sample Content</span>

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

零基础学Java -〔臧萌〕

Linux实战技能100讲 -〔尹会生〕

研发效率破局之道 -〔葛俊〕

移动端自动化测试实战 -〔思寒〕

架构实战案例解析 -〔王庆友〕

手机摄影 -〔@随你们去〕

实用密码学 -〔范学雷〕

玩转Vue 3全家桶 -〔大圣〕

快手 · 移动端音视频开发实战 -〔展晓凯〕

好记忆不如烂笔头。留下您的足迹吧 :)