文適合有 Java 基礎知識的人群
本文作者:HelloGitHub-秦人
HelloGitHub 推出的《講解開源項目》系列,今天給大家帶來一款開源 Java 版一款網頁元素解析框架——jsoup,通過程序自動獲取網頁數據。
項目源碼地址:https://github.com/jhy/jsoup
jsoup 是一款 Java 的 HTML 解析器。可直接解析某個 URL 地址的 HTML 文本內容。它提供了一套很省力的 API,可通過 DOM、CSS 以及類似于 jQuery 選擇器的操作方法來取出和操作數據。
jsoup 主要功能:
將項目導入 idea 開發工具,會自動下載 maven 項目需要的依賴。源碼的項目結構如下:
快速學習源碼是每個程序員必備的技能,我總結了以下幾點:
git clone https://github.com/jhy/jsoup
通過上面的方法,我們很快可知 example 目錄是測試代碼,那我們直接來運行。注:有些測試代碼需要稍微改造一下才可以運行。
例如,jsoup 的 Wikipedia 測試代碼:
public class Wikipedia {
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
log(doc.title());
Elements newsHeadlines = doc.select("#mp-itn b a");
for (Element headline : newsHeadlines) {
log("%s\n\t%s", headline.attr("title"), headline.absUrl("href"));
}
}
private static void log(String msg, String... vals) {
System.out.println(String.format(msg, vals));
}
}
說明:上面代碼是獲取頁面(http://en.wikipedia.org/)包含(#mp-itn b a)選擇器的所有元素,并打印這些元素的 title , herf 屬性。維基百科 國內無法訪問,所以上面這段代碼運行會報錯。
改造后可運行的代碼如下:
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("https://www.baidu.com/").get();
Elements newsHeadlines = doc.select("a[href]");
for (Element headline : newsHeadlines) {
System.out.println("href: " +headline.absUrl("href") );
}
}
Jsoup 的工作原理,首先需要指定一個 URL,框架發送 HTTP 請求,然后獲取響應頁面內容,然后通過各種選擇器獲取頁面數據。整個工作流程如下圖:
以上面為例:
Document doc = Jsoup.connect("https://www.baidu.com/").get();
這行代碼就是發送 HTTP 請求,并獲取頁面響應數據。
Elements newsHeadlines = doc.select("a[href]");
定義選擇器,獲取匹配選擇器的數據。
for (Element headline : newsHeadlines) {
System.out.println("href: " +headline.absUrl("href") );
}
這里對數據只做了一個簡單的數據打印,當然這些數據可寫入文件或數據的。
獲取豆瓣讀書 -> 新書速遞中每本新書的基本信息。包括:書名、書圖片鏈接、作者、內容簡介(詳情頁面)、作者簡介(詳情頁面)、當當網書的價格(詳情頁面),最后將獲取的數據保存到 Excel 文件。
目標鏈接:https://book.douban.com/latest?icn=index-latestbook-all
項目引入 jsoup、lombok、easyexcel 三個庫。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>JsoupTest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
</dependencies>
</project>
public class BookInfoUtils {
public static List<BookEntity> getBookInfoList(String url) throws IOException {
List<BookEntity> bookEntities=new ArrayList<>();
Document doc = Jsoup.connect(url).get();
Elements liDiv = doc.select("#content > div > div.article > ul > li");
for (Element li : liDiv) {
Elements urls = li.select("a[href]");
Elements imgUrl = li.select("a > img");
Elements bookName = li.select(" div > h2 > a");
Elements starsCount = li.select(" div > p.rating > span.font-small.color-lightgray");
Elements author = li.select("div > p.color-gray");
Elements description = li.select(" div > p.detail");
String bookDetailUrl = urls.get(0).attr("href");
BookDetailInfo detailInfo = getDetailInfo(bookDetailUrl);
BookEntity bookEntity = BookEntity.builder()
.detailPageUrl(bookDetailUrl)
.bookImgUrl(imgUrl.attr("src"))
.bookName(bookName.html())
.starsCount(starsCount.html())
.author(author.text())
.bookDetailInfo(detailInfo)
.description(description.html())
.build();
// System.out.println(bookEntity);
bookEntities.add(bookEntity);
}
return bookEntities;
}
/**
*
* @param detailUrl
* @return
* @throws IOException
*/
public static BookDetailInfo getDetailInfo(String detailUrl)throws IOException{
Document doc = Jsoup.connect(detailUrl).get();
Elements content = doc.select("body");
Elements price = content.select("#buyinfo-printed > ul.bs.current-version-list > li:nth-child(2) > div.cell.price-btn-wrapper > div.cell.impression_track_mod_buyinfo > div.cell.price-wrapper > a > span");
Elements author = content.select("#info > span:nth-child(1) > a");
BookDetailInfo bookDetailInfo = BookDetailInfo.builder()
.author(author.html())
.authorUrl(author.attr("href"))
.price(price.html())
.build();
return bookDetailInfo;
}
}
這里的重點是要獲取網頁對應元素的選擇器。
例如:獲取 li.select("div > p.color-gray") 中 div > p.color-gray 是怎么知道的。
使用 chrome 的小伙伴應該都猜到了。打開 chrome 瀏覽器 Debug 模式,Ctrl + Shift +C 選擇一個元素,然后在 html 右鍵選擇 Copy ->Copy selector,這樣就可以獲取當前元素的選擇器。如下圖:
為了數據更好查看,我將通過 jsoup 抓取的數據存儲的 Excel 文件,這里我使用的 easyexcel 快速生成 Excel 文件。
Excel 表頭信息
@Data
@Builder
public class ColumnData {
@ExcelProperty("書名稱")
private String bookName;
@ExcelProperty("評分")
private String starsCount;
@ExcelProperty("作者")
private String author;
@ExcelProperty("封面圖片")
private String bookImgUrl;
@ExcelProperty("簡介")
private String description;
@ExcelProperty("單價")
private String price;
}
生成 Excel 文件
public class EasyExcelUtils {
public static void simpleWrite(List<BookEntity> bookEntityList) {
String fileName = "D:\\devEnv\\JsoupTest\\bookList" + System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, ColumnData.class).sheet("書本詳情").doWrite(data(bookEntityList));
System.out.println("excel文件生成完畢...");
}
private static List<ColumnData> data(List<BookEntity> bookEntityList) {
List<ColumnData> list = new ArrayList<>();
bookEntityList.forEach(b -> {
ColumnData data = ColumnData.builder()
.bookName(b.getBookName())
.starsCount(b.getStarsCount())
.author(b.getBookDetailInfo().getAuthor())
.bookImgUrl(b.getBookImgUrl())
.description(b.getDescription())
.price(b.getBookDetailInfo().getPrice())
.build();
list.add(data);
});
return list;
}
}
最終的效果如下圖:
以上就是從想法到實踐,我們就在實戰中使用了 jsoup 的基本操作。
完整代碼地址:https://github.com/hellowHuaairen/JsoupTest
Java HTML Parser 庫:jsoup,把它當成簡單的爬蟲用起來還是很方便的吧?
為什么會講爬蟲?大數據,人工智能時代玩的就是數據,數據很重要。作為懂點技術的我們,也需要掌握一種獲取網絡數據的技能。當然也有一些工具 Fiddler、webscraper 等也可以抓取你想要的數據。
教程至此,你應該也能對 jsoup 有一些感覺了吧。編程是不是也特別有意思呢?參考我上面的實戰案例,有好多網站可以實踐一下啦~歡迎在評論區曬你的實戰。
制方法效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery復制節點相關的方法</title>
<script src="../static/js/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(function(){
/*
clone([Even[,deepEven]]) 克隆匹配的DOM元素并且選中這些克隆的副本
如果傳入false就是淺復制,如果傳入true就是深復制
淺復制只會復制元素,而深復制也會復制元素的事件
*/
$('button').eq(0).click(function(){
// 1. 淺復制一個元素
var $li = $('li:first').clone(false)
// 2. 將復制的元素添加到ul當中
$('ul').append($li)
})
$('button').eq(1).click(function(){
var $li = $('li:first').clone(true) // 深復制最后的參數是true 深復制的節點連里面的方法也復制了
// 2. 將復制的元素添加到ul當中
$('ul').append($li)
})
$('li').click(function(){
alert($(this).html())
})
})
</script>
</head>
<body>
<button>淺復制節點</button>
<button>深復制節點</button>
<ul>
<li>我是第1個li</li>
<li>我是第2個li</li>
<li>我是第3個li</li>
<li>我是第4個li</li>
<li>我是第5個li</li>
</ul>
</body>
</html>
一、我們先做一個列表,并且添加好外鏈jQuery庫。
圖1
二、做列表項的點擊事件,事件內是空的。
圖2
三、我們檢驗一下點擊效果。
圖3
圖4
四、現在我們換成復制元素節點,用的是clone()。
圖5
圖6
五、于是你發現元素節點可以復制了,但復制出來的節點點擊沒有效果。
圖7
*請認真填寫需求信息,我們會在24小時內與您取得聯系。