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)设置htmlouterHtml() 获得内部htmldata()获得数据内容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.后端处理后返回的样式

springboot使用Jsoup解析html相关推荐

  1. SpringBoot集成jsoup多线程爬取美剧天堂全部电影资源

    SpringBoot集成jsoup爬取美剧天堂全部美剧资源 准备工作 这次我的目的是获取这个网站的所有美剧的信息和迅雷的BT地址,我们需要获取的信息都在上万个类似于下面个页面结构的页面上 确定了目标, ...

  2. ElasticSearch(五)SpringBoot+ES+Jsoup实现JD(京东)搜索

    标题SpringBoot+ES+Jsoup实现JD搜索 文章目录 标题SpringBoot+ES+Jsoup实现JD搜索 1.功能概述 2.工具简介 3.操作步骤 4.总结 项目效果 1.功能概述 ​ ...

  3. 关于Jsoup解析https网页的问题

    针对Jsoup解析https网页,网上的一段源码执行后并不能实现成功访问. import java.net.MalformedURLException; import java.net.URL; im ...

  4. Jsoup介绍||​​​​​​​jsoup解析url || Jsoup解析字符串||​​​​​​​Jsoup解析文件

    Jsoup 抓取到页面之后,还需要对页面进行解析.可以使用字符串处理工具解析页面,也可以使用正则表达式,但是这些方法都会带来很大的开发成本,所以我们需要使用一款专门解析html页面的技术. jsoup ...

  5. Android利用Jsoup解析html 开发网站客户端小记。

    这些天业余时间比较多,闲来无事,想起了以前看过开发任意网站客户端的一篇文章,就是利用jsoup解析网站网页,通过标签获取想要的内容.好了废话不多说,用到的工具为 jsoup-1.7.2.jar包,具体 ...

  6. 【爬蟲】使用Jsoup解析文档

    [爬蟲]使用Jsoup解析文档

  7. Android开发探秘之三:利用jsoup解析HTML页面

    这节主要是讲解jsoup解析HTML页面.由于在android开发过程中,不可避免的涉及到web页面的抓取,解析,展示等等,所以,在这里我主要展示下利用jsoup jar包来抓取cnbeta.com网 ...

  8. Andorid中使用Jsoup解析库解析XML、HTML、Dom节点---第三方库学习笔记(三)

    XML介绍: XML简介: XML,可扩展标记语言,标准通用标记语言的子集. 一种用于标记电子文件使其具有结构性的标记语言. 它可以用来标记数据.定义数据类型 是一种允许用户对自己的标记语言进行定义的 ...

  9. XML解析——Jsoup解析器

    一.Jsoup解析器快速入门案例 Docement对象,文本对象,包含着各个Dom树结构 1.引入Jsoup解析器的jar包放在lib文件夹下后,写java代码 其中, 二.Jsoup对象 1.Jso ...

最新文章

  1. 题解 UVA11354 【Bond】
  2. django 三天写个人博客
  3. PAT1052 卖个萌 (20 分)【别人的代码 借鉴从字符串中截取特定部分的思路】
  4. python数据库模糊查询_Python操作mongodb数据库进行模糊查询操作示例
  5. mysql load average_紧急求助:load average太高了!!
  6. juery 常用方法
  7. Spring-IOC推导
  8. python解析GF1卫星数据.xml文件
  9. 拓端tecdat|R语言使用K-Means聚类可视化WiFi访问
  10. echo命令的15个用法
  11. 银行柜员网申计算机水平要求高吗,银行笔试通过率:看你网申如何?
  12. 金融工程与并行计算:第二章 仿真法在财务工程的使用 Part 2
  13. 如何学习三点透视?该注意什么?
  14. java项目:基于springboot+vue的实验室预约管理系统 nodejs
  15. Tensorflow深度学习学习笔记
  16. maven如何排除依赖
  17. linux和数据库day01随堂笔记
  18. linux下ddos软件,Linux 系统下ddos软件Zarp安装测试
  19. 【水果识别】基于matlab GUI苹果分级系统(带面板)【含Matlab源码 1827期】
  20. 好玩有趣的软件,居家无聊必备

热门文章

  1. JavaScript---Web学习总结
  2. [链表]链表寻找中间点环形链表反转链表
  3. Win10安装OneDrive(微软云盘)后无法打开
  4. 基于微信小程序的汽车俱乐部系统的设计与实现_kaic
  5. 添加公司信息-公司宣传型小程序源代码下载1-视频教程24
  6. 揭秘电销机器人那些不为人知的秘密
  7. Artistic Style 使用教程(中文版)
  8. 特权级保护和任务切换
  9. java中OOD_Java面向对象OOD
  10. ElasticSearch基础概念及工作流程