突發靈感,看到某網站的搞笑圖片挺多,作了一個小java,掃描摳了一些html
這裏分享一下java
/** * 取得文件的後綴名 * @Description: TODO * @param countStr * @return */ private static String getFileExt(String fileStr){ return fileStr.substring(fileStr.lastIndexOf(".") + 1).toLowerCase(); }
獲得文件後綴,保存用網站
/** * 取得不一樣的頁面地址 * @Description: TODO * @param countStr * @return */ private static String getPagePath(String countStr){ String pagPath = "http://xxx.xxxx.xxxx.xxx/thread-2:count-1-1.html"; return pagPath.replaceAll(":count", countStr); }
取得頁面地址this
/** * 取得圖片的url地址 * @Description: TODO * @param contextStr * @return */ private static String getImgSrc(String contextStr){ if(contextStr.indexOf("\" onload=\"thumbImg(this)\"")<0){ return null; } String bigStr = contextStr.substring(contextStr.indexOf("\" onload=\"thumbImg(this)\"")-74,contextStr.indexOf("\" onload=\"thumbImg(this)\"")); String imgStr = bigStr.substring(bigStr.indexOf("<img src=\"")+10); return imgStr; }
解析頁面代碼,將圖片的url地址取出url
/** * 下載圖片 * @param f 保存的文件 * @param imgUrl 圖片地址 */ public static void downloadFile(File f, String imgUrl) { byte[] buffer = new byte[8 * 1024]; URL u; URLConnection connection = null; try { u = new URL(imgUrl); connection = u.openConnection(); } catch (Exception e) { System.out.println("ERR:" + imgUrl); return; } InputStream is = null; FileOutputStream fos = null; try { f.createNewFile(); is = connection.getInputStream(); fos = new FileOutputStream(f); int len = 0; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); f.delete(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } if (is != null) { try { is.close(); } catch (IOException e) { } } } buffer = null; // System.gc(); }
將url圖片下載到本地
完整代碼下載:http://download.csdn.net/detail/songylwq/4738238
.net