(转)jsoup使用教程

原文:https://blog.csdn.net/justLym/article/details/105715516

jsoup是一款Java的html解析工具,主要是对html和xml文件进行解析
在写爬虫的时候,当我们用HttpClient之类的框架,得到目标网页的源码后,需要从网页源码中取得我们想要的内容。就可以使用jsoup轻松获取想要的内容。

jsoup的中文开发文档

获取jsoup的maven方式
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
1
2
3
4
5
6
从URL获取HTML来解析
// 方式一
Document document = Jsoup.connect("http://www.baidu.com/").get();

// 方式二
Document parse = Jsoup.parse(new URL("http://www.baidu.com/"), 1000 * 10);
1
2
3
4
5
其中Jsoup.connect(“xxx”)方法返回一个org.jsoup.Connection对象。
在Connection对象中,我们可以执行get和post来执行请求。但在执行请求之前,我们可以使用Connection对象来设置一些请求信息。比如:头信息,cookie,请求等待时间,代理等等模拟浏览器行为。

Document document = Jsoup.connect("http://www.baidu.com/")
.data("wd","我")
.userAgent("Mozilla")
.cookie("auth","token")
.timeout(3000)
.post();
1
2
3
4
5
6
从文件中获取html来解析
Document path = Jsoup.parse(new File("path"), "utf-8");
1
直接从字符串中获得html来解析
Document text = Jsoup.parse("");
1
通过Document获取指定节点Element对象
通过方法来查找指定的节点Element
// 通过元素id值来获取对应的节点
Element element = document.getElementById(String id);

// 通过标签名来获取
Elements elements = document.getElementsByTag(String tagName);

// 通过类名来获取
Elements elements = document.getElementsByClass(String className);

// 通过属性名来获取
Elements elements = document.getElementsByAttribute(String key);

// 通过指定属性名称和属性值来获取节点对象
Elements elements = document.getElementsByAttributeValue(String key, String value);

// 获取所有节点元素
Elements elements = document.getAllElements();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
通过类似于css或者jQuery的选择器来查找元素
public Elements select(String cssQuery) {
return Selector.select(cssQuery, this);
}

File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

//带有href属性的a元素
Elements links = doc.select("a[href]");

//扩展名为.png的图片
Elements pngs = doc.select("img[src$=.png]");

//class等于masthead的div标签
Element masthead = doc.select("div.masthead").first();

//在h3元素之后的a元素
Elements resultLinks = doc.select("h3.r > a");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
通过传入一个类似于css或者jQuery的选择器字符串,来查找指定元素
选择器中更多语法可以在org.jsoup.select.Selector中查看到更多关于选择器的语法

Selector中的语法简介
tagName:通过标签名查找元素,比如:a
ns|tag:通过标签在命名空间查找元素,比如:可以用fb|name语法来查找<fb:name>元素
#id:通过ID来查找元素,比如#logo
.class:通过class名称来查找元素 比如.master
[attribute]:利用属性名称来查找元素,如[href]
[^attribute]:利用属性前缀来查找元素,比如:可以用[^data-]来查找带有HTML中以data-开头的属性节点
[attr=value]:利用属性值来查找元素,比如:[width=500]
[attr~=regx]:利用属性值匹配正则表达式来查找元素,比如:img[src~=(?i).(png|jpe?g)]
*:这个符号将匹配所有元素

Selector选择器组合使用
el#id:元素+ID,比如:div#logo
el.class:元素+class,比如:div.master
el[attr]:元素+attr,比如:a[href]
任意组合,比如:a[href].heightlight
ancestor 空格 child:查找某个元素下的子元素,比如:可以用body p查找body下的所有p标签
parent > child:查找某个父元素下的直接元素,比如:可以用div.content > p查找class是content的div中所有的p标签
siblingA + siblingB:查找标签A下的第一个B标签,比如:div.head + div
siblingA ~ siblingB:查找siblingA同级第一个B标签,比如:h1 ~ p
el,el,el:多个选择器组合,查找匹配任一选择器的唯一元素,例如:div.master,div.logo

Selector伪类选择器
tag:lt(n):查找所有小于给定索引值的元素,从0开始计数,比如tr:lt(2)
tag:gt(n):查找所有大于给定索引值的元素,从0开始计数,比如tr:gt(2)
tag:eq(n):查找给定索引值的元素,比如tr:eq(2)
tag:has(seletor):查找匹配选择器包含元素的元素,比如:div:has§表示哪些div包含p元素
tag:not(seletor):查找于选择器不匹配的元素,比如:div:not(.logo)表示不包含class=”logo“元素的所有div列表
tag:contains(text):查找包含给定文本元素,搜索不区分大小写,比如:p:contains(jsoup)
tag:containsOwn(text):查找直接包含指定文本的元素
tag:matches(regex):查找自身包含文本匹配指定的元素

通过上面的选择器,我们可以取得一个Elements对象中,它继承了ArrayList对象,里面放的全是Element对象。

使用Element获得想要的内容
// 这个方法用来获取一个元素中的文本
element.text()

// 这个方法用来获取一个元素中的html内容
element.html()或Node.outerHtml()

// 这个方法来取得一个元素的一个属性值
Node.attr(String key)
1
2
3
4
5
6
7
8
package com.justLym.demo.jsoup;

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

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
* @author justLym
* @version 1.0.0 2020/4/23 19:44
**/
public class JsoupMain {
public static void main(String[] args) {
try {
Document document = Jsoup.connect("http://www.baidu.com/")
.data("wd","我")
.userAgent("Mozilla")
.cookie("auth","token")
.timeout(3000)
.post();

Elements elements = document.select("a");

elements.forEach(element -> {
System.out.println(element.text());
});


} catch (IOException e) {
e.printStackTrace();
}
}
}

 
posted @ 2022-07-17 14:57  liujiacai  阅读(651)  评论(0编辑  收藏  举报