一個(gè)很簡單的網(wǎng)站圖片抓取功能
全部使用jdk的基本功能,沒有用任何包
不要談什么效率,什么規(guī)范,要的就是立即看懂,拿著就改
不好意思,連正則都懶得用
也沒用開源的爬蟲軟件。。。。。。
主要分兩部分
1.找出連接
public class GetWebContent {
/**
* 獲取html內(nèi)容
* @param domain
* @return
*/
public static String getWebCon(String path) {
// System.out.println("開始讀取內(nèi)容...("+domain+")");
StringBuffer sb = new StringBuffer();
try {
java.net.URL url = new java.net.URL(path);
BufferedReader in = new BufferedReader(new InputStreamReader(url
.openStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
} catch (Exception e) { // Report any errors that arise
sb.append(e.toString());
System.err.println(e);
System.err
.println("Usage: java HttpClient <URL> [<filename>]");
}
return sb.toString();
}
/**
* 下載指定格式鏈接
* @param path 圖片所在網(wǎng)頁
* @param begin 圖片路徑開始
* @param end 圖片路徑結(jié)尾
*/
public static void uploadImage(String path,String begin,String end){
Map<String,String> map=new HashMap<>();
String a=getWebCon(path);
String[] as=a.split(begin);
for (int j = 1; j < as.length-1; j++) {
String xxx = as[j].split(end)[0];
String url=begin+xxx+end;
if (map.containsKey(url)) continue;
try {
DownloadImage.download(url);
map.put(url, "111");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
2.下載圖片
public class DownloadImage {
private static final String FILE_PATH="D:\\image\\";
public static void download(String urlString) throws Exception {
// 構(gòu)造URL
String filename=System.currentTimeMillis()+"-"+(int)(Math.random()*10000)+".jpg";
String savePath=FILE_PATH;
URL url = new URL(urlString);
// 打開連接
URLConnection con = url.openConnection();
//設(shè)置請求超時(shí)為5s
con.setConnectTimeout(5*1000);
// 輸入流
InputStream is = con.getInputStream();
// 1K的數(shù)據(jù)緩沖
byte[] bs = new byte[1024];
// 讀取到的數(shù)據(jù)長度
int len;
// 輸出的文件流
File sf=new File(savePath);
if(!sf.exists()){
sf.mkdirs();
}
OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
// 開始讀取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完畢,關(guān)閉所有鏈接
os.close();
is.close();
}
}