Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
文適合有 Java 基礎(chǔ)知識(shí)的人群
本文作者:HelloGitHub-秦人
HelloGitHub 推出的《講解開源項(xiàng)目》系列,今天給大家?guī)硪豢铋_源 Java 版一款網(wǎng)頁元素解析框架——jsoup,通過程序自動(dòng)獲取網(wǎng)頁數(shù)據(jù)。
項(xiàng)目源碼地址:https://github.com/jhy/jsoup
jsoup 是一款 Java 的 HTML 解析器。可直接解析某個(gè) URL 地址的 HTML 文本內(nèi)容。它提供了一套很省力的 API,可通過 DOM、CSS 以及類似于 jQuery 選擇器的操作方法來取出和操作數(shù)據(jù)。
jsoup 主要功能:
將項(xiàng)目導(dǎo)入 idea 開發(fā)工具,會(huì)自動(dòng)下載 maven 項(xiàng)目需要的依賴。源碼的項(xiàng)目結(jié)構(gòu)如下:
快速學(xué)習(xí)源碼是每個(gè)程序員必備的技能,我總結(jié)了以下幾點(diǎn):
git clone https://github.com/jhy/jsoup
通過上面的方法,我們很快可知 example 目錄是測(cè)試代碼,那我們直接來運(yùn)行。注:有些測(cè)試代碼需要稍微改造一下才可以運(yùn)行。
例如,jsoup 的 Wikipedia 測(cè)試代碼:
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 屬性。維基百科 國內(nèi)無法訪問,所以上面這段代碼運(yùn)行會(huì)報(bào)錯(cuò)。
改造后可運(yùn)行的代碼如下:
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 的工作原理,首先需要指定一個(gè) URL,框架發(fā)送 HTTP 請(qǐng)求,然后獲取響應(yīng)頁面內(nèi)容,然后通過各種選擇器獲取頁面數(shù)據(jù)。整個(gè)工作流程如下圖:
以上面為例:
Document doc = Jsoup.connect("https://www.baidu.com/").get();
這行代碼就是發(fā)送 HTTP 請(qǐng)求,并獲取頁面響應(yīng)數(shù)據(jù)。
Elements newsHeadlines = doc.select("a[href]");
定義選擇器,獲取匹配選擇器的數(shù)據(jù)。
for (Element headline : newsHeadlines) {
System.out.println("href: " +headline.absUrl("href") );
}
這里對(duì)數(shù)據(jù)只做了一個(gè)簡單的數(shù)據(jù)打印,當(dāng)然這些數(shù)據(jù)可寫入文件或數(shù)據(jù)的。
獲取豆瓣讀書 -> 新書速遞中每本新書的基本信息。包括:書名、書圖片鏈接、作者、內(nèi)容簡介(詳情頁面)、作者簡介(詳情頁面)、當(dāng)當(dāng)網(wǎng)書的價(jià)格(詳情頁面),最后將獲取的數(shù)據(jù)保存到 Excel 文件。
目標(biāo)鏈接:https://book.douban.com/latest?icn=index-latestbook-all
項(xiàng)目引入 jsoup、lombok、easyexcel 三個(gè)庫。
<?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;
}
}
這里的重點(diǎn)是要獲取網(wǎng)頁對(duì)應(yīng)元素的選擇器。
例如:獲取 li.select("div > p.color-gray") 中 div > p.color-gray 是怎么知道的。
使用 chrome 的小伙伴應(yīng)該都猜到了。打開 chrome 瀏覽器 Debug 模式,Ctrl + Shift +C 選擇一個(gè)元素,然后在 html 右鍵選擇 Copy ->Copy selector,這樣就可以獲取當(dāng)前元素的選擇器。如下圖:
為了數(shù)據(jù)更好查看,我將通過 jsoup 抓取的數(shù)據(jù)存儲(chǔ)的 Excel 文件,這里我使用的 easyexcel 快速生成 Excel 文件。
Excel 表頭信息
@Data
@Builder
public class ColumnData {
@ExcelProperty("書名稱")
private String bookName;
@ExcelProperty("評(píng)分")
private String starsCount;
@ExcelProperty("作者")
private String author;
@ExcelProperty("封面圖片")
private String bookImgUrl;
@ExcelProperty("簡介")
private String description;
@ExcelProperty("單價(jià)")
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;
}
}
最終的效果如下圖:
以上就是從想法到實(shí)踐,我們就在實(shí)戰(zhàn)中使用了 jsoup 的基本操作。
完整代碼地址:https://github.com/hellowHuaairen/JsoupTest
Java HTML Parser 庫:jsoup,把它當(dāng)成簡單的爬蟲用起來還是很方便的吧?
為什么會(huì)講爬蟲?大數(shù)據(jù),人工智能時(shí)代玩的就是數(shù)據(jù),數(shù)據(jù)很重要。作為懂點(diǎn)技術(shù)的我們,也需要掌握一種獲取網(wǎng)絡(luò)數(shù)據(jù)的技能。當(dāng)然也有一些工具 Fiddler、webscraper 等也可以抓取你想要的數(shù)據(jù)。
教程至此,你應(yīng)該也能對(duì) jsoup 有一些感覺了吧。編程是不是也特別有意思呢?參考我上面的實(shí)戰(zhàn)案例,有好多網(wǎng)站可以實(shí)踐一下啦~歡迎在評(píng)論區(qū)曬你的實(shí)戰(zhàn)。
AVA中將WORD轉(zhuǎn)換為HTML導(dǎo)入到WANGEDITOR編輯器中(解決圖片問題,樣式,非常完美),wangEditor如何導(dǎo)入word文檔,如何實(shí)現(xiàn)導(dǎo)入WORD文檔到WANGEDITOR編輯器中?WANGEDITOR導(dǎo)入WORD文檔 WANGEDITOR WORD導(dǎo)入插件,HTML富文本編輯器導(dǎo)入WORD,Web富文本編輯器導(dǎo)入WORD,WANGEDITOR富文本編輯器導(dǎo)入WORD,WANGEDITOR導(dǎo)入WORD,WANGEDITORWORD導(dǎo)入編輯,wangEditor集成word導(dǎo)入功能,
后端是用的JAVA,SpringBoot框架,實(shí)際上前端在集成的時(shí)候是不關(guān)心后端具體是用什么語言實(shí)現(xiàn)的。
它這個(gè)版本有幾個(gè)wangEditor3,wangEditor4,wangEditor5,好用的是就3和4,5不支持插入HTML。但是用戶用插入HTML這個(gè)功能用的比較多。
vue-cli-wangEditor3,vue3-cli-wangEditor4集成word導(dǎo)入功能。在VUE框架下面集成了WORD導(dǎo)入功能。
用戶選擇word文件后,自動(dòng)轉(zhuǎn)換成html,自動(dòng)將word里面的圖片上傳到服務(wù)器中,自動(dòng)將HTML添加到編輯器中。
主要的方案就是提供一個(gè)轉(zhuǎn)換接口,轉(zhuǎn)換接口使用RESTful協(xié)議,這樣的話兼容性更好一點(diǎn),其它的平臺(tái)用起來的話更方便簡單一點(diǎn),而且測(cè)試起來也方便。
現(xiàn)有項(xiàng)目需要為TinyMCE增加導(dǎo)入word文件的功能,導(dǎo)入后word文件里面的圖片自動(dòng)上傳到服務(wù)器中,返回圖片和文字HTML,word里面的文本樣式保留
用戶一般在發(fā)新聞和發(fā)文章時(shí)用到,算是一個(gè)高頻使用功能,用戶體驗(yàn)上來講確實(shí)是很好,和以前的發(fā)新聞或者發(fā)文章的體驗(yàn)比起來要方便許多,用戶用的更爽。
1.下載示例
https://gitee.com/xproer/zyoffice-vue3-cli-wang-editor4
2.引入組件
3.添加按鈕
4.配置轉(zhuǎn)換接口
效果
開發(fā)文檔:https://drive.weixin.qq.com/s?k=ACoAYgezAAwsDazDKJ
產(chǎn)品比較:https://drive.weixin.qq.com/s?k=ACoAYgezAAwh8oq8Zf
產(chǎn)品源代碼:https://drive.weixin.qq.com/s?k=ACoAYgezAAwjJM8412
報(bào)價(jià)單:https://drive.weixin.qq.com/s?k=ACoAYgezAAwsfyDdrf
文介紹如何通過Java后端程序代碼來展示如何將html轉(zhuǎn)為XML。此功能通過采用Word API- Free Spire.Doc for Java 提供的Document.saveToFile()方法來實(shí)現(xiàn);該方法支持的目標(biāo)文檔格式多達(dá) 30余種。另外,該API也提供了多種方法,如Document.saveToEpub()、Document.saveToFile()、Document.saveToImages()、Document.saveToSVG()、Document.saveToTxt()、Document.saveToTiff()等,可用于將源文件轉(zhuǎn)為Epub、圖片、文本文件等目標(biāo)文檔格式。
下面,將以html轉(zhuǎn)為xml格式為例,介紹如何實(shí)現(xiàn)轉(zhuǎn)換。以下是詳細(xì)方法及步驟。
通過 Maven倉庫 下載導(dǎo)入,如下配置pom.xml:
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
如需手動(dòng)導(dǎo)入,需要下載 jar包 到本地,然后解壓,找到lib文件夾下的Spire.Doc.jar文件。在IDEA中打開“Project Structure”界面,執(zhí)行如圖步驟將本地路徑下的jar文件手動(dòng)引入Java程序:
轉(zhuǎn)換時(shí),可參考如下代碼步驟:
Java
import com.spire.doc.*;
public class HTMLtoXML {
public static void main(String[] args) {
//創(chuàng)建Document類的對(duì)象
Document doc=new Document();
//加載html文件
doc.loadFromFile("sample.html",FileFormat.Html);
//保存為XML格式
doc.saveToFile("HTMLtoXML.xml", FileFormat.Xml);
}
}
轉(zhuǎn)換效果:
—END—
原文出處:https://www.cnblogs.com/Yesi/p/16392430.html
如果本文對(duì)你有幫助,別忘記給我個(gè)3連 ,點(diǎn)贊,轉(zhuǎn)發(fā),評(píng)論,
學(xué)習(xí)更多JAVA知識(shí)與技巧,關(guān)注與私信博主(555),即可免費(fèi)領(lǐng)取
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。