
Java爬蟲,就先爬個好爬的豆瓣讀書的封面。
Java jsoup多線程爬蟲(爬豆瓣圖書封面)
利用線程池多線程爬,biubiubiu,速度超快。
下載到指定的文件夾中。
App.java:
package com.newer.spider;
import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class App { public static void main(String[] args) { // 確定目標地址 URL 統一資源定位符 String url="https://book.douban.com/"; // 2 解析 html : https://jsoup.org try { // Document doc = Jsoup.connect(url).get(); // System.out.println(doc.title()); // System.out.println(doc.html()); //從 Doc 的樹形結構中查找 img 標簽 //.class 選擇器 Elements els = doc.select(".cover img"); System.out.println(els.size()); // 創建一個線程池 //.class 選擇器 ExecutorService pool = Executors.newCachedThreadPool(); pool = Executors.newFixedThreadPool(9); // pool = Executors.newSingleThreadExecutor(); for(Element e : els) { // <img src="" width="" height="" /> String src = e.attr("src"); System.out.println(src); // 下載每張圖片 pool.execute(new DownloadTask(src)); } //釋放資源 pool.shutdown(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.newer.spider;
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; /** * 負責下載圖片的任務,可以由線程執行 (Runnable) * * @author zmz * */ public class DownloadTask implements Runnable { //圖片的路徑 String imagePath; /** * * @param src * 圖片的位置和路徑 */ public DownloadTask(String src) { imagePath = src; } @Override public void run() { //建立一個HTTP連接,使用輸入流獲得數據,使用輸出流寫入磁盤 HttpURLConnection conn = null; InputStream in = null; FileOutputStream out = null; try { conn = (HttpURLConnection) new URL(imagePath).openConnection(); //讀取數據 in = conn.getInputStream(); String uu = "G:\\Newer_Project\\Spider\\img\\"; //獲得圖片的名字 int index = imagePath.lastIndexOf('/'); String file = imagePath.substring(index + 1); file = uu + file; //創建輸出流,寫入 out = new FileOutputStream(file); byte[] buf = new byte[1024 + 16]; int size; while(-1 != (size = in.read(buf))) { out.write(buf, 0, size); } //下載完成 String name = Thread.currentThread().getName(); System.out.println(name + "下載" + imagePath); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //不論是否發生異常都會執行的 if(out != null) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn != null) { conn.disconnect(); } } } }
后續是不是可以翻頁爬的,因為這個只是爬當前頁面的,豆瓣讀書網的書還有很多頁,我們爬完這一頁的,繼續爬下一頁?
