Jsoup解析html,java基础入门教学

这里我们要用到HttpClient来获取网页内容:

gradle 配置:

//添加 httpclient 支持

// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

compile group: ‘org.apache.httpcomponents’, name: ‘httpclient’, version: ‘4.5.7’

//添加 jsoup 支持

// https://mvnrepository.com/artifact/org.jsoup/jsoup

compile group: ‘org.jsoup’, name: ‘jsoup’, version: ‘1.11.3’

maven 项目:

org.apache.httpcomponents

httpclient

4.5.7

org.jsoup

jsoup

1.11.3

/**

  • 输入一个网址返回这个网址的字符串

*/

public String getHtml(String str) throws IOException {

CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httpclient实例

HttpGet httpget = new HttpGet(str); // 创建httpget实例

CloseableHttpResponse response = httpclient.execute(httpget); // 执行get请求

HttpEntity entity = response.getEntity(); // 获取返回实体

String content = EntityUtils.toString(entity, “utf-8”);

response.close(); // 关闭流和释放系统资源

return content;

}

/**

  • 爬取 博客园

  • 1、网页标题

  • 2、口号

*/

@Test

public void test() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements elements = doc.getElementsByTag(“title”); // 获取tag是title的所有DOM元素

Element element = elements.get(0); // 获取第1个元素

String title = element.text(); // 返回元素的文本

System.out.println(“网页标题:” + title);

Element element2 = doc.getElementById(“site_nav_top”); // 获取id=site_nav_top的DOM元素

String navTop = element2.text(); // 返回元素的文本

System.out.println(“口号:” + navTop);

}

输出:

网页标题:博客园 - 代码改变世界

口号:代码改变世界

/**

  • 获取文章的 url

*/

@Test

public void test5() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements linkElements = doc.select("#post_list .post_item .post_item_body h3 a"); //通过选择器查找所有博客链接DOM

for (Element e : linkElements) {

System.out.println(e.attr(“href”));

}

}

三、Jsoup查找DOM元素


Jsoup提供了丰富的API来给我们查找我们需要的DOM元素,常用的如下:

getElementById(Stringid) 根据 id 来查询 DOM

getElementsByTag(StringtagName) 根据 tag 名称来查询 DOM

getElementsByClass(StringclassName) 根据样式名称来查询 DOM

getElementsByAttribute(Stringkey) 根据属性名来查询 DOM

getElementsByAttributeValue(Stringkey,Stringvalue) 根据属性名和属性值来查询 DOM

/**

  • Jsoup 查找 DOM 元素

*/

@Test

public void test2() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements itemElements = doc.getElementsByClass(“post_item”); // 根据样式名称来查询DOM

System.out.println("=输出post_item========");

for (Element e : itemElements) {

System.out.println(e.html());//获取里面所有的 html 包括文本

System.out.println("\n");

}

Elements widthElements = doc.getElementsByAttribute(“width”); // 根据属性名称来查询DOM(id class type 等),用的少一般很难找用这种方法

System.out.println("=输出with的DOM========");

for (Element e : widthElements) {

System.out.println(e.toString());//不能用 e.html() 这里需要输出 DOM

}

//

Elements targetElements = doc.getElementsByAttributeValue(“target”, “_blank”);

System.out.println("=输出target-_blank的DOM========");

for (Element e : targetElements) {

System.out.println(e.toString());

}

}

四、Jsoup使用选择器语法查找DOM元素


我们前面通过标签名,Id,Class样式等来搜索DOM,这些是不能满足实际开发需求的,很多时候我们需要寻找有规律的DOM集合,很多个有规律的标签层次,这时候,选择器就用上了。css jquery 都有,Jsoup支持css,jquery类似的选择器语法。

/**

  • 有层级关系

*/

@Test

public void test3() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements linkElements = doc.select("#post_list .post_item .post_item_body h3 a"); //通过选择器查找所有博客链接DOM(范围重小到大)

for (Element e : linkElements) {

System.out.println(“博客标题:” + e.text());//超链接的内容

}

System.out.println("--------------------带有href属性的a元素--------------------------------");

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

for (Element e : hrefElements) {

System.out.println(e.toString());

}

System.out.println("------------------------查找扩展名为.png的图片----------------------------");

Elements imgElements = doc.select(“img[src$=.png]”); // 查找扩展名为.png的图片DOM节点

for (Element e : imgElements) {

System.out.println(e.toString());

}

System.out.println("------------------------获取第一个元素----------------------------");

Element element = doc.getElementsByTag(“title”).first(); // 获取tag是title的所有DOM元素

String title = element.text(); // 返回元素的文本

System.out.println(“网页标题是:” + title);

}

![](https://img-blog.csdnimg.cn/20200929203337198.pn

【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】

浏览器打开:qq.cn.hn/FTf 免费领取

g?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1b3J1aV9qYXZh,size_16,color_FFFFFF,t_70)

五、Jsoup获取DOM元素属性值


/**

  • 获取 DOM 元素属性值

*/

@Test

public void test4() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements linkElements = doc.select("#post_list .post_item .post_item_body h3 a"); //通过选择器查找所有博客链接DOM

for (Element e : linkElements) {

System.out.println(“博客标题:” + e.text());//获取里面所有的文本

System.out.println(“博客地址:” + e.attr(“href”));

System.out.println(“target:” + e.attr(“target”));

}

System.out.println("------------------------友情链接----------------------------");

Element linkElement = doc.select("#friend_link").first();

System.out.println(“纯文本:” + linkElement.text());//去掉 html

System.out.println("------------------------Html----------------------------");

System.out.println(“Html:” + linkElement.html());

}

/**

  • 获取文章的 url

*/

@Test

public void test5() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements linkElements = doc.select("#post_list .post_item .post_item_body h3 a"); //通过选择器查找所有博客链接DOM

for (Element e : linkElements) {

System.out.println(e.attr(“href”));

}

}

注意:Element 的几个获取内容的方法区别

  1. text()            获取的是去掉了 html 元素,也就是只用元素内容

  2. toString()      DOM

  3. html()          获取里面所有的 html 包括文本

import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.jsoup.Jsoup;

import org.jsoup.nodes.Document;

import org.jsoup.nodes.Element;

import org.jsoup.select.Elements;

import org.junit.Test;

import java.io.IOException;

public class Main {

/**

  • 输入一个网址返回这个网址的字符串

*/

public String getHtml(String str) throws IOException {

CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httpclient实例

HttpGet httpget = new HttpGet(str); // 创建httpget实例

CloseableHttpResponse response = httpclient.execute(httpget); // 执行get请求

HttpEntity entity = response.getEntity(); // 获取返回实体

String content = EntityUtils.toString(entity, “utf-8”);

response.close(); // 关闭流和释放系统资源

return content;

}

/**

  • 爬取 博客园

  • 1、网页标题

  • 2、口号

*/

@Test

public void test() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements elements = doc.getElementsByTag(“title”); // 获取tag是title的所有DOM元素

Element element = elements.get(0); // 获取第1个元素

String title = element.text(); // 返回元素的文本

System.out.println(“网页标题:” + title);

Element element2 = doc.getElementById(“site_nav_top”); // 获取id=site_nav_top的DOM元素

String navTop = element2.text(); // 返回元素的文本

System.out.println(“口号:” + navTop);

}

/**

  • Jsoup 查找 DOM 元素

*/

@Test

public void test2() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

Elements itemElements = doc.getElementsByClass(“post_item”); // 根据样式名称来查询DOM

System.out.println("=输出post_item========");

for (Element e : itemElements) {

System.out.println(e.html());//获取里面所有的 html 包括文本

System.out.println("\n");

}

Elements widthElements = doc.getElementsByAttribute(“width”); // 根据属性名称来查询DOM(id class type 等),用的少一般很难找用这种方法

System.out.println("=输出with的DOM========");

for (Element e : widthElements) {

System.out.println(e.toString());//不能用 e.html() 这里需要输出 DOM

}

//

Elements targetElements = doc.getElementsByAttributeValue(“target”, “_blank”);

System.out.println("=输出target-_blank的DOM========");

for (Element e : targetElements) {

System.out.println(e.toString());

}

}

/**

  • 有层级关系

*/

@Test

public void test3() throws IOException {

Document doc = Jsoup.parse(getHtml(“http://www.cnblogs.com/”)); // 解析网页 得到文档对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值