Springboot 解析 json 并返回+ Jsoup介绍及解析常用方法

摘要:
1、配置pom.xmlorg.jsoupjsoup1.11.2com.alibabafastjson˂versi

1、配置pom.xml

    <dependency>
             <groupId>org.jsoup</groupId>
             <artifactId>jsoup</artifactId>
             <version>1.11.2</version>
    </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.9</version>
        </dependency>

2、编写模型类

1 packagecom.example.model;
2 
3 public classNewBean {
4     privateString title;
5     privateString content;
6     privateString imgUrl;
7     privateString urlA;
8 
9     publicNewBean() {
10 
11 }
12 
13     publicNewBean(String title, String content,
14 String imgUrl, String urlA) {
15         super();
16         this.title =title;
17         this.content =content;
18         this.imgUrl =imgUrl;
19         this.urlA =urlA;
20 }
21 
22     publicString getTitle() {
23         returntitle;
24 }
25 
26     public voidsetTitle(String title) {
27         this.title =title;
28 }
29 
30     publicString getContent() {
31         returncontent;
32 }
33 
34     public voidsetContent(String content) {
35         this.content =content;
36 }
37 
38     publicString getImgUrl() {
39         returnimgUrl;
40 }
41 
42     public voidsetImgUrl(String imgUrl) {
43         this.imgUrl =imgUrl;
44 }
45 
46     publicString getUrlA() {
47         returnurlA;
48 }
49 
50     public voidsetUrlA(String urlA) {
51         this.urlA =urlA;
52 }
53 
54 @Override
55     publicString toString() {
56         return "NewBean:[title=" + title + ", content=" + content + ", imgUrl=" + imgUrl + "urlA" + urlA + "]";
57 }
58 }

3、编写控制类

1 packagecom.example.controller;
2 
3 importjava.util.ArrayList;
4 importjava.util.List;
5 
6 importorg.springframework.boot.autoconfigure.SpringBootApplication;
7 importorg.springframework.web.bind.annotation.RequestMapping;
8 importorg.springframework.web.bind.annotation.RestController;
9 importjava.io.IOException;
10 
11 importorg.jsoup.Jsoup;
12 importorg.jsoup.nodes.Document;
13 importorg.jsoup.nodes.Element;
14 importorg.jsoup.select.Elements;
15 
16 importcom.alibaba.fastjson.JSON;
17 importcom.example.model.NewBean;
18 
19 @SpringBootApplication
20 @RestController
21 public classSpringTestApplication {
22 
23     @RequestMapping("hello")
24     publicString hello(){
25         return "hello";
26 }
27     
28     
29     @RequestMapping("json")
30     public static String getNew(inti) {
31         String url = "http://www.cnmo.com/news/all_" + i + ".html";
32         List<NewBean> list_bean = new ArrayList<>();
33 NewBean newbean;
34         try{
35             Document doc =Jsoup.connect(url).get();
36             //获取class等于Newcon的div标签
37             Element contents = doc.select("div.Newcon").first();
38             Elements content = contents.getElementsByClass("Newcon-list");
39             for(Element element : content) {
40                 Elements linka = element.getElementsByTag("a");
41                 String linkHref = linka.get(0).attr("href");
42                 String linkText = linka.get(0).text();
43                 Elements linkimg = element.getElementsByTag("img");
44                 String linkSrc = linkimg.get(0).attr("src");
45                 Elements linkp = element.getElementsByTag("p");
46                 String linktxt = linkp.get(0).text();
47                 //这里把内部类修饰为static所以直接new
48                 newbean = newNewBean(linkText, linktxt, linkSrc, linkHref);
49 list_bean.add(newbean);
50 }
51             //使用了阿里的fastJson,其它json框架也可以,true是格式化
52             String json = JSON.toJSONString(list_bean, true);
53             returnjson;
54         } catch(IOException e) {
55             //e.printStackTrace();
56             return null;
57 }
58 }
59     
60     
61 }

4、编写启动类

packagecom.example.controller;

importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public classSpringDemoApplication {

    public static voidmain(String[] args) {
        SpringApplication.run(SpringDemoApplication.class, args);
    }
}

Jsoup介绍及解析常用方法

jsoup 是一款 Java 的HTML 解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于JQuery的操作方法来取出和操作数据
jsoup的主要功能如下:
从一个URL,文件或字符串中解析HTML;
使用DOM或CSS选择器来查找、取出数据;
可操作HTML元素、属性、文本;
jsoup解析
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表示字符集
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) 设置请求来源
jsoup提供类似JS获取html元素:
getElementById(String id) 用id获得元素
getElementsByTag(String tag) 用标签获得元素
getElementsByClass(String className) 用class获得元素
getElementsByAttribute(String key) 用属性获得元素
同时还提供下面的方法提供获取兄弟节点:siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling()
获得与设置元素的数据
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
操作html元素:
append(String html), prepend(String html)
appendText(String text), prependText(String text)
appendElement(String tagName), prependElement(String tagName)
html(String value)
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)]
以上是最基本的选择器语法,这些语法也可以组合起来使用
组合用法
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
除了一些基本的语法以及这些语法进行组合外,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) 表示不包含 元素的所有 div 列表
:contains(text) 包含某文本的元素,不区分大小写,例如 p:contains(oschina)
:containsOwn(text) 文本信息完全等于指定条件的过滤
:matches(regex) 使用正则表达式进行文本过滤:div:matches((?i)login)

:matchesOwn(regex) 使用正则表达式找到自身的文本

——————————————————————————————————————————————————————————
//url网址作为输入源
Document doc = Jsoup.connect("http://www.example.com").timeout(60000).get();
//File文件作为输入源
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://www.example.com/");
//String作为输入源
Document doc = Jsoup.parse(htmlStr);
和java script类似,Jsoup提供了下列的函数
getElementById(String id) 通过id获得元素
getElementsByTag(String tag) 通过标签获得元素
getElementsByClass(String className) 通过class获得元素
getElementsByAttribute(String key) 通过属性获得元素
同时还提供下面的方法提供获取兄弟节点:
siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling()
用下面方法获得元素的数据:
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

操作html提供了下面方法:
append(String html), prepend(String html)
appendText(String text), prependText(String text)
appendElement(String tagName), prependElement(String tagName)
html(String value)

免责声明:文章转载自《Springboot 解析 json 并返回+ Jsoup介绍及解析常用方法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇超详细Vue实现导航栏绑定内容锚点+滚动动画+vue-router(hash模式可用)C#+arcengine获得栅格数据的像素值(高程)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Java 性能优化的 50 个细节

在JAVA程序中,性能问题的大部分原因并不在于JAVA语言,而是程序本身。养成良好的编码习惯非常重要,能够显著地提升程序性能。 #尽量在合适的场合使用单例 使用单例可以减轻加载的负担,缩短加载的时间,提高加载的效率,但并不是所有地方都适用于单例 简单来说,单例主要适用于以下三个方面: 控制资源的使用,通过线程同步来控制资源的并发访问; 控制实例的产生,以...

Gson的入门使用

Java对象和Json之间的互转,一般用的比较多的两个类库是Jackson和Gson,下面记录一下Gson的学习使用。 基础概念:  Serialization:序列化,使Java对象到Json字符串的过程。  Deserialization:反序列化,字符串转换成Java对象   使用Maven管理Gson,pom.xml导入gson的依赖 <...

System.Web.Mvc 找到的程序集清单定义与程序集引用不匹配

System.IO.FileLoadException: 未能加载文件或程序集“System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)文...

11-C#反射机制

C#反射机制 转自:http://blog.csdn.net/educast/article/details/2894892 反射的用途:    (1)使用Assembly定义和加载程序集,加载在程序集清单中列出模块,以及从此程序集中查找类型并创建该类型的实例。     (2)使用Module了解包含模块的程序集以及模块中的类等,还可以获取在模块上定义的所...

交易所如何对接狗狗币(DOGE)钱包?这点不可忽视

一个大家非常熟悉的 meme 头像 doge 在一夜之间成为了全球热搜。在国内,「狗狗币一天暴涨逾 250%」登上了微博热搜第七位,在国外,「DOGE」或者「DOGECOIN」站上了多个地区的「推特趋势榜」。比特币似乎都没有如此高规格的待遇。   对于新入币圈的朋友们可能对狗狗币还不太熟悉。这个币是个很早期的山寨币,它基本上是比特币的翻版,但是在比特币的基...

公众号第三方平台开发 component_verify_ticket和accessToken的获取

公众号第三方平台审核通过之后,微信的服务器会定时(10分钟一次)给"授权事件接收URL"发送component_verify_ticket,这里我们需要及时更新component_verify_ticket 就是下面这个链接 下面这里是我的处理函数 private void ResponseRequest() { //WX...