一、前言
把一篇圖文并茂的優秀文章全部爬取下來,就少不了 Java 爬蟲裡邊的 圖檔爬取 技術了。很多人都用來爬取美女圖檔,但是筆者覺得這有傷大雅。下面筆者使用它來爬取 CSDN 【今日推薦】文章附帶的圖檔

二、代碼、依賴
筆者對本代碼經過多次修訂,邏輯可以說是最簡單的了,但性能上可能就算不上是最優的了,基本用法都注釋在代碼裡邊,該注意的地方都打 ✔ 了
①目錄
(使用 SpringBoot 建立的工程,當然也可以使用 Java Project、web Project、Maven Project)
② 代碼
package com.cun.test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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;
/**
* 1、使用 HttpClient 擷取網頁文檔對象
* 2、使用 Jsoup 擷取所需的資訊
* 3、不足:沒有判斷圖檔類型,但是沒什麼影響
* @author linhongcun
*
*/
public class JsoupHttpClient {
public static void main(String[] args) throws ClientProtocolException, IOException {
// 建立httpclient執行個體
CloseableHttpClient httpclient = HttpClients.createDefault();
// 建立httpget執行個體
HttpGet httpget = new HttpGet("https://www.csdn.net/");
// 執行get請求
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
// 擷取傳回實體
String content = EntityUtils.toString(entity, "utf-8");
// 解析網頁 得到文檔對象
Document doc = Jsoup.parse(content);
// 擷取指定的 <img />
Elements elements = doc.select(".img_box img");
for (int i = ; i < ; i++) {
Element element = elements.get(i);
// 擷取 <img /> 的 src
String url = element.attr("src");
// 再發請求最簡單了,并由于該連結是沒有 https:開頭的,得人工補全 ✔
HttpGet PicturehttpGet = new HttpGet("https:" + url);
CloseableHttpResponse pictureResponse = httpclient.execute(PicturehttpGet);
HttpEntity pictureEntity = pictureResponse.getEntity();
InputStream inputStream = pictureEntity.getContent();
// 使用 common-io 下載下傳圖檔到本地,注意圖檔名不能重複 ✔
FileUtils.copyToFile(inputStream, new File("C://LLLLLLLLLLLLLLLLLLL//imagesTest//" + i + ".jpg"));
pictureResponse.close(); // pictureResponse關閉
}
response.close(); // response關閉
httpclient.close(); // httpClient關閉
}
}
③ pom 依賴
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<!-- 檔案下載下傳 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
三、效果
四、小結
1、優化:
可以根據圖檔的字尾 .jpg、.png、.gif 儲存相應格式的圖檔到本地,不要一味 .jpg 結尾儲存
2、附上 CSDN 首頁部分源碼
3、爬蟲資源先放到本地,再放到伺服器,否則對伺服器 CPU 消耗巨大,伺服器成本高