package com.obcy.service;
import com.obcy.util.DownLoad;
import com.obcy.util.GetHTML;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class BiAn {
//獲取到所有的一級頁面,從第2頁到第946頁
public ArrayList<String> getTopUrl(){
//String topurl = "http://www.netbian.com/hd3840x2160/index_2.htm"
//定義一個集合保存所有的一級頁面
ArrayList<String> list = new ArrayList<String>();
for (int i = 2; i <= 946; i++) {
list.add("http://www.netbian.com/hd3840x2160/index_"+i+".htm");
}
return list;
}
//獲取一級頁面的所有圖片查看地址
//傳入的參數是一級頁面地址
public HashMap<String,String> getGpjView(String topUrl){
String url = topUrl;
String html = GetHTML.getHTML(url);
//獲取到網頁源代碼document對象
Document document = Jsoup.parse(html);
//解析document對象,拿到頁面每個圖片查看地址
Elements list = document.getElementsByClass("list");
//拿到的list只有一個對象,這個對象裏包含頁面所有的圖片a標籤
Elements a = null;
try {
a = list.get(0).select("ul>li>a");
} catch (Exception e) {
System.out.println("沒有獲取到a標籤");
}
//遍歷a標籤對象,拿到a標籤的href屬性值並拼接成完整的圖片查看地址放入集合裏
//建立一個map集合
HashMap<String,String> map = new HashMap<String, String>();
for (int i = 0; i < a.size(); i++) {
String href = "http://www.netbian.com"+a.get(i).attr("href");
String name = a.get(i).attr("title");
//System.out.println(href);http://www.netbian.com/desk/22138.htm
map.put(name,href);
}
//蒐集本頁面的圖片查看地址完成
return map;
}
//訪問每個一級頁面,獲取到頁面裏所有的圖片下載地址,
// 方法接收一個裝有一個一級頁面所有圖片查看地址的集合
public void getDownload(HashMap<String,String> map){
//遍歷集合,對集合裏所有的頁面進行提取,每個頁面提取到一張圖片下載地址,並下載
for (Map.Entry<String, String> entry : map.entrySet()) {
String html = GetHTML.getHTML(entry.getValue());
Document document = Jsoup.parse(html);
//拿到圖片img標籤對象,只有一個
Elements endpage = null;
try {
endpage = document.getElementsByClass("endpage").get(0).select("div>p>a>img");
} catch (Exception e) {
System.out.println("沒獲取到頁面對象,繼續下一個");
continue;
}
//System.out.println(endpage.get(0).attr("src"));
//得到下載地址
String target = endpage.get(0).attr("src");
String path = "F:/BiAn/"+entry.getKey()+".jpg";
//開始下載
DownLoad.downLoad(target,path);
}
}
@Test
public void test(){
//判斷是否存在文件夾F:/BiAn
File file = new File("F:/BiAn");
if (!file.exists()){
file.mkdirs();
System.out.println("已創建下載文件夾F:/BiAn");
}else {
System.out.println("已存在文件夾,具備下載條件");
}
//單線程
//拿到所有一級頁面
ArrayList<String> topUrl = getTopUrl();
//對每個頁面進行操作,1.得到視圖集合,2.遍歷集合,拿到下載地址,3.下載
for (String url : topUrl) {
HashMap<String, String> gpjView = getGpjView(url);
getDownload(gpjView);
}
}
}