標籤:trace des 抓取 www org exception java 擷取資料 timeout
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import org.jsoup.Connection;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;// 爬取圖片 public class Baidu { public static void main(String[] args) { String urlPath = "http://www.*****.com/chemo/2043_2.html"; int index = 2; for (int j = 0; j <= 20; j++) { urlPath = "http://www.****.com/chemo/2043_" + (index++) + ".html"; File f = new File("F:/imgs"); if (!f.exists()) { f.mkdirs(); } Document doc; try { doc = Jsoup.connect(urlPath).timeout(10000).get(); // 擷取尾碼為jpg的圖片的元素集合 Elements pngs = doc.select("img[src$=.jpg]"); // 遍曆元素 for (Element e : pngs) { String src = e.attr("src");// 擷取img中的src路徑 // 擷取尾碼名 String imageName = src.substring(src.lastIndexOf("/") + 1, src.length()); // 串連url URL url; try { url = new URL(src); URLConnection uri = url.openConnection(); // 擷取資料流 InputStream is = uri.getInputStream(); // 寫入資料流 OutputStream os = new FileOutputStream(new File( "F:/imgs", imageName)); byte[] buf = new byte[3072]; int i = 0; while ((i = is.read()) != -1) { os.write(i); } os.close(); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } catch (IOException e2) { e2.printStackTrace(); } } }}
這裡用的是jsoup1.6.3jar
研究了一天時間,說說碰到的難題。我這裡抓取的是以.jpg為主的圖片.
當時沒有擷取圖片的尾碼名,每次往電腦上下載圖片總是建立一個空的檔案夾。一定要擷取到圖片的尾碼名才行。
還有一點就是我這個方法不一定適合所有的網站,不同網站的src地址不一樣,需要注意一下。
我這個是有20多頁的圖片,簡單用了個迴圈,每頁的地址都有規律,找到規律就手到擒來了。
剛研究,如有高手,還望賜教。
jsoup擷取圖片樣本