springboot使用Jsoup解析html

springboot使用Jsoup解析html

1.需求
前端传至后端的html数据,需要后端解析并替换值
2.解决
使用 Jsoup

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.15.4</version>
</dependency>

3.Jsoup的主要功能
1)从一个URL,文件或字符串中解析HTML
2)使用DOM或CSS选择器来查找、取出数据
3)可操作HTML元素、属性、文本
注意:jsoup是基于MIT协议发布的,可放心使用于商业项目。
4.使用
4.1.通过url加载

/* get方式 */
 /* Document doc = Jsoup.connect("http://www.baidu.com/").get(); */
 /* post方式 */
 /* Document doc = Jsoup.connect("http://www.baidu.com/").post(); */
 /* 添加参数等请求信息 */
 Document doc = Jsoup.connect("http://www.baidu.com/")
    .data("user", "test")
    .cookie("user", "test")
    .timeout(3000)
    .post();

4.2.通过文件加载

 File f = new File("input.html");
 /* 第三个参数用于处理相对路径 */
 Document doc = Jsoup.parse(f, "UTF-8", "http://www.baidu.com/");

4.3.通过字符串加载

 String html = "<html><head><title></title></head><body></body></html>";
 Document doc = Jsoup.parse(html);

5.解析
Jsoup提供一系列的静态解析方法生成Document对象

 static Document parse(File in, String charsetName)
 static Document parse(File in, String charsetName, String baseUri)
 static Document parse(InputStream in, String charsetName, String baseUri)
 static Document parse(String html)
 static Document parse(String html, String baseUri)   
 static Document parse(URL url, int timeoutMillis)
 static Document parseBodyFragment(String bodyHtml)
 static Document parseBodyFragment(String bodyHtml, String baseUri) 

其中baseUri表示检索到的相对URL是相对于baseUriURL的
其中charsetName表示字符集
6.Connection connect(String url) 根据给定的url(必须是http或https)来创建连接
Connection 提供一些方法来抓去网页内容

Connection cookie(String name, String value) 发送请求时放置cookie 
Connection data(Map<String,String> data) 传递请求参数 
Connection data(String... keyvals) 传递请求参数
Document get() 以get方式发送请求并对返回结果进行解析
Document post()以post方式发送请求并对返回结果进行解析 
Connection userAgent(String userAgent) 
Connection header(String name, String value) 添加请求头
Connection referrer(String referrer) 设置请求来源

7.jsoup提供类似JS获取html元素:

getElementById(String id) 用id获得元素
getElementsByTag(String tag) 用标签获得元素
getElementsByClass(String className) 用class获得元素
getElementsByAttribute(String key)  用属性获得元素
同时还提供下面的方法提供获取兄弟节点:
siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling()

8.获得与设置元素的数据

 attr(String key)  获得元素的数据 attr(String key, String value) 设置元素数据 
 attributes() 获得所以属性
 id(), className()  classNames() 获得id class得值
 text()获得文本值
 text(String value) 设置文本值
 html() 获取html 
 html(String value)设置html
 outerHtml() 获得内部html
 data()获得数据内容
 tag()  获得tag 和 tagName() 获得tagname 

9.操作html元素:

 append(String html), prepend(String html)
 appendText(String text), prependText(String text)
 appendElement(String tagName), prependElement(String tagName)
 html(String value)

10.Jsoup还提供了类似于JQuery方式的选择器,采用选择器来检索数据

 tagname    使用标签名来定位,例如 a 
 ns|tag     使用命名空间的标签定位,例如 fb:name 来查找 <fb:name> 元素 
 #id        使用元素 id 定位,例如 #logo 
 .class     使用元素的 class 属性定位,例如 .head 
 *          定位所有元素 
 [attribute] 使用元素的属性进行定位,例如 [href] 表示检索具有 href 属性的所有元素 
 [^attr]     使用元素的属性名前缀进行定位,例如 [^data-] 用来查找 HTML5 的 dataset 属性 
 [attr=value]使用属性值进行定位,例如 [width=500] 定位所有 width 属性值为 500 的元素 
 [attr^=value],[attr$=value],[attr*=value] 这三个语法分别代表,属性以 value 开头、结尾以及包含 
 [attr~=regex]使用正则表达式进行属性值的过滤,例如 img[src~=(?i)\.(png|jpe?g)] 
 以上是最基本的选择器语法,这些语法也可以组合起来使用

11.组合用法

el#id      定位id值某个元素,例如 a#logo -> <a id=logo href= … > 
el.class 定位 class 为指定值的元素,例如 div.head -> <div class=head>xxxx</div> 
el[attr] 定位所有定义了某属性的元素,例如 a[href] 
以上三个任意组合     例如 a[href]#logo 、a[name].outerlink 

12.除了一些基本的语法以及这些语法进行组合外,jsoup 还支持使用表达式进行元素过滤选择

 :lt(n)     例如 td:lt(3) 表示小于三列 
 :gt(n)     div p:gt(2) 表示 div 中包含 2 个以上的 p 
 :eq(n)     form input:eq(1) 表示只包含一个 input 的表单 
 :has(seletor)     div:has(p) 表示包含了 p 元素的 div 
 :not(selector)     div:not(.logo) 表示不包含 class=logo 元素的所有 div 列表 
 :contains(text)     包含某文本的元素,不区分大小写,例如 p:contains(oschina) 
 :containsOwn(text)     文本信息完全等于指定条件的过滤 
 :matches(regex)     使用正则表达式进行文本过滤:div:matches((?i)login) 
 :matchesOwn(regex)     使用正则表达式找到自身的文本 

13.和java script类似,Jsoup提供了下列的函数

 getElementById(String id) 通过id获得元素  
 getElementsByTag(String tag) 通过标签获得元素  
 getElementsByClass(String className) 通过class获得元素  
 getElementsByAttribute(String key) 通过属性获得元素  

14.同时还提供下面的方法提供获取兄弟节点:

 siblingElements();
 firstElementSibling();
 lastElementSibling();
 nextElementSibling();
 previousElementSibling();

15.用下面方法获得元素的数据:

 attr(String key) 获得元素的数据  
 attr(String key, String value) 设置元素数据  
 attributes() 获得所有属性  
 id(), className() classNames() 得到id class的值  
 text()得到文本值  
 text(String value) 设置文本值  
 html() 获取html   
 html(String value)设置html  
 outerHtml() 获得内部html  
 data()获得数据内容  
 tag() 得到tag 和 tagName() 得到tagname 

16.操作html提供了下面方法:

 append(String html), prepend(String html)  
 appendText(String text), prependText(String text)  
 appendElement(String tagName), prependElement(String tagName)  
 html(String value) 

17.项目中使用
17.1.传入后端的数据

<p style="text-align: center;">念奴娇·赤壁怀古</p><p>&nbsp; &nbsp; &nbsp; &nbsp; 大江东去,浪淘尽,千古风流人物。故垒西边,人道是:三国周郎赤壁。乱石穿空,惊涛拍岸,卷起千堆雪。江山如画,一时多少豪杰。</p><p>&nbsp; &nbsp; &nbsp; &nbsp; 遥想公瑾当年,小乔初嫁了,雄姿英发。羽扇纶巾,谈笑间、樯橹灰飞烟灭。故国神游,多情应笑我,早生华发。人生如梦,一尊还酹江月。&nbsp;</p><p><br></p><p>姓名<span id="customer_name" title="顾客姓名" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;customer_name&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客姓名&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customerName" title="顾客姓名" style="color:#000000;" class="sde-value" contenteditable="true">顾客姓名</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span></p><p>电话<span id="custom_phone" title="顾客电话" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;custom_phone&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客电话&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customPhone" title="顾客电话" style="color:#000000;" class="sde-value" contenteditable="true">顾客电话</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span>
</p>

17.2.后端从数据库中获取的数据

{"customPhone":"15693167830","customerName":"张丹丹"}

17.3.后端解析替换的数据

<p style="text-align: center;">念奴娇·赤壁怀古</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; 大江东去,浪淘尽,千古风流人物。故垒西边,人道是:三国周郎赤壁。乱石穿空,惊涛拍岸,卷起千堆雪。江山如画,一时多少豪杰。</p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; 遥想公瑾当年,小乔初嫁了,雄姿英发。羽扇纶巾,谈笑间、樯橹灰飞烟灭。故国神游,多情应笑我,早生华发。人生如梦,一尊还酹江月。&nbsp;</p>
<p><br></p>
<p>姓名<span id="customer_name" title="顾客姓名" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;customer_name&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客姓名&quot;}" contenteditable="false" class="sde-bg"> <span class="sde-left" style="color:#0000FF" contenteditable="false">[</span> <span id="customerName" title="顾客姓名" style="color:#000000;" class="sde-value" contenteditable="true">张丹丹</span> <span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span></p>
<p>电话<span id="custom_phone" title="顾客电话" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;custom_phone&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客电话&quot;}" contenteditable="false" class="sde-bg"> <span class="sde-left" style="color:#0000FF" contenteditable="false">[</span> <span id="customPhone" title="顾客电话" style="color:#000000;" class="sde-value" contenteditable="true">15693167830</span> <span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span></p>

17.4.后端处理代码

// 从数据库中获取的需要替换填充的数据,以 JSONObject 获取
JSONObject json = XXXX

// html 为前端传入后端的数据
String s = new String(html);
// 通过 Jsoup 转为 Document 
Document document = Jsoup.parse(s);
// 遍历 数据库中获取的填充数据
Iterator<String> iterator = json.keySet().iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    // 根据元素中的 id 赋值
    document.getElementById(key).text(json.getString(key));
}
// 通过 p 标签获取元素
Elements pEl = document.getElementsByTag("p");

17.4.1.id重复的处理
前端代码

<p style="white-space: normal; text-align: center;">念奴娇 赤壁怀古</p><p style="white-space: normal;"><br></p><p style="white-space: normal;">&nbsp; &nbsp; &nbsp; &nbsp; 大江东去,浪淘尽,千古风流人物。故垒西边,人道是:三国周郎赤壁。乱石穿空,惊涛拍岸,卷起千堆雪。江山如画,一时多少豪杰。</p><p style="white-space: normal;">&nbsp; &nbsp; &nbsp; &nbsp; 遥想公瑾当年,小乔初嫁了,雄姿英发。羽扇纶巾,谈笑间、樯橹灰飞烟灭。故国神游,多情应笑我,早生华发。人生如梦,一尊还酹江月。</p><p style="white-space: normal;"><br></p><p style="white-space: normal;">姓名<span id="customer_name" title="顾客姓名" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;customer_name&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客姓名&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customerName" title="顾客姓名" style="color:#000000;" class="sde-value" contenteditable="true">顾客姓名</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span>&nbsp; &nbsp; &nbsp;紧急联系人姓名<span id="customer_name" title="顾客姓名" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;customer_name&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客姓名&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customerName" title="顾客姓名" style="color:#000000;" class="sde-value" contenteditable="true">顾客姓名</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span></p><p style="white-space: normal;">家属姓名<span id="customer_name" title="顾客姓名" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;customer_name&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客姓名&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customerName" title="顾客姓名" style="color:#000000;" class="sde-value" contenteditable="true">顾客姓名</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span>&nbsp; &nbsp; &nbsp; 电话<span id="custom_phone" title="顾客电话" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;custom_phone&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客电话&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customPhone" title="顾客电话" style="color:#000000;" class="sde-value" contenteditable="true">顾客电话</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span></p><p style="white-space: normal;">紧急联系人电话<span id="custom_phone" title="顾客电话" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;custom_phone&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客电话&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customPhone" title="顾客电话" style="color:#000000;" class="sde-value" contenteditable="true">顾客电话</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span>&nbsp; &nbsp; 家属电话<span id="custom_phone" title="顾客电话" sde-model="{&quot;tableSchema&quot;:&quot;confinement&quot;,&quot;tableName&quot;:&quot;customer_cmt&quot;,&quot;columnName&quot;:&quot;custom_phone&quot;,&quot;dataType&quot;:&quot;text&quot;,&quot;value&quot;:&quot;顾客电话&quot;}" contenteditable="false" class="sde-bg">
	<span class="sde-left" style="color:#0000FF" contenteditable="false">[</span>
	<span id="customPhone" title="顾客电话" style="color:#000000;" class="sde-value" contenteditable="true">顾客电话</span>
	<span style="color:#0000FF" contenteditable="false" class="sde-right">]</span></span>
</p>
Document document = Jsoup.parse(s);
Elements pList = document.getElementsByTag("p");
// 主要处理数据重复 即 标签的 id 重复
for(Element p:pList){ // 跨行重复
    Iterator<String> iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        Element elementById = p.getElementById(key);

        if(elementById != null){
            Elements span = p.getElementsByTag("span");
            for(Element sp:span){ // 同行重复
                Element byId = sp.getElementById(key);
                if(byId !=null){
                    byId.text(map.get(key).toString());
                }
            }
        }
    }
}

在这里插入图片描述

17.5.前端传入时的样式
在这里插入图片描述
17.6.后端处理后返回的样式
在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值