import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* 通過HTML解析實現圖片批量下載
* @author haikui
* @version v1.0
* @date 2019年6月10日
*/
public class HtmlJsoup {
/**
* 第一步:獲取頁面的源代碼;
* 第二步:解析源代碼,含有圖片的標籤,再找到圖片標籤裏面的src或data-imgurl;
* 第三步:利用Java裏面的net包,網絡編程
* */
/**
* 根據網頁和編碼獲取網頁內容和源代碼
* @param url
* @param encoding
*/
public static String getHtmlResourceByUrl(String url,String encoding){
StringBuffer buffer = new StringBuffer();
URL urlObj = null;
URLConnection uCon = null;
InputStreamReader in = null;
BufferedReader reader = null;
try {
// 建立網絡連接
urlObj = new URL(url);
// 創建輸入流
in =new InputStreamReader(urlObj.openStream(),encoding);
// 創建一個緩衝寫入流
reader = new BufferedReader(in);
String line = null;
while ((line = reader.readLine()) != null) {
// 一行一行追加
buffer.append(line+"\r\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return buffer.toString();
}
/**
* 功能:Java讀取txt文件的內容
* 步驟:1:先獲得文件句柄
* 2:獲得文件句柄當做是輸入一個字節碼流,需要對這個輸入流進行讀取
* 3:讀取到輸入流後,需要讀取生成字節流
* 4:一行一行的輸出。readline()。
* 備註:需要考慮的是異常情況
* @param filePath
*/
public static String readTxtFile(String filePath){
StringBuffer buffer = new StringBuffer();
try {
String encoding="utf-8";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判斷文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考慮到編碼格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
buffer.append(lineTxt+"\r\n");
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("讀取文件內容出錯");
e.printStackTrace();
}
return buffer.toString();
}
/**
* 根據圖片的URL下載的圖片到本地的filePath
* @param filePath 文件夾
* @param imageUrl 圖片的網址
*/
public static void downImages(String filePath,String imageUrl){
// 截取圖片的名稱
String fileName = imageUrl.substring(imageUrl.lastIndexOf("/"));
//創建文件的目錄結構
File files = new File(filePath);
if(!files.exists()){// 判斷文件夾是否存在,如果不存在就創建一個文件夾
files.mkdirs();
}
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
// 創建文件
File file = new File(filePath+fileName);
FileOutputStream out = new FileOutputStream(file);
int i = 0;
while((i = is.read()) != -1){
out.write(i);
}
is.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//執行測試程序代碼
public static void main(String[] args) {
//以下被註釋的內容可以作爲一種測試方法使用,這裏直接在txt中粘貼html源碼測試
/*Scanner input = new Scanner(System.in);
System.out.print("請輸入網頁地址:");
String url = input.nextLine();
System.out.print("請輸入編碼方式:");
String encoding = input.nextLine();
System.out.print("請輸入下載到電腦的位置:");
String filePath = input.nextLine();*/
int count=0;
//String url = "https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%B2%F1%C8%AE%CD%BC%C6%AC&fr=ala&ala=1&alatpl=adress&pos=0&hs=2&xthttps=111111";
//String encoding = "utf-8";
String filePath ="/Users/wangyaoxin/Desktop/圖片";
//String htmlResource = getHtmlResourceByUrl(url, encoding);
String htmlResource=readTxtFile("/Users/wangyaoxin/Desktop/htmlResource2.txt");
// 解析網頁源代碼
Document document = Jsoup.parse(htmlResource);
// 獲取所有圖片的地址
Elements elements = document.getElementsByTag("img");
for(Element element : elements){
//具體圖片url的元素屬性看html源碼,這裏的URL是在data-imgurl中
String imgSrc = element.attr("data-imgurl");
if (!"".equals(imgSrc) && (imgSrc.startsWith("http://") || imgSrc.startsWith("https://"))) {
// 判斷imgSrc是否爲空且是否以"http://"或"https://"開頭
System.out.println("正在下載的圖片的地址:" + imgSrc);
downImages(filePath, imgSrc);
count++;
}
}
System.out.println("共下載"+count+"張圖片");
System.out.println("-------------------------下載完畢!----------------------------");
}
}
使用詳解:
1、通過getHtmlResourceByUrl方法,獲取到網頁源碼再解析下載圖片,實際使用過程中發現獲取到的源碼不全,所以選擇第二種方法
2、把html源碼複製到txt文件中,用readTxtFile方法讀取文件內容,再調用downImages下載
- Google瀏覽器,F12查看源代碼,複製html源碼到本地到txt文件中
- 修改main方法測試代碼中filePath爲本地放置下載圖片的文件夾,readTxtFile()參數爲txt文件路徑,element.attr()參數爲圖片URL前的key值