批量下載音效

緣由:需要一些聲音素材,搜索到站長之家裏面有很多素材,但是一個一個下載太麻煩了,而且下載完還要手動改名,甭提多麻煩了。

於是重複的事情交給機器來做好了。

在頁面上鼠標移上去可以試聽聲音的效果,下面有聲音的名字,於是想到可以通過解析html,自動下載,保存爲對應的文件名。 吐舌頭

分析HTML得知,整個在id爲"musiclist"的div裏,每個音效文件對應裏面的一個class爲"music_block"的div,再裏面的第一個<p>的thumb即是音效文件的下載地址,音效文件名在第2個<p>裏包含着。

用JS試着取

var blocks=document.getElementById("musiclist").getElementsByClassName("music_block");
blocks[0].innerText//取得文件名
blocks[0].childNodes[1].getAttribute("thumb")//取得文件下載地址


Java的話用Jsoup(http://jsoup.org/)解析HTML很好用

Document doc = Jsoup.connect(pageURL).get();
Elements blocks = doc.getElementById("musiclist").getElementsByClass("music_block");
int length = blocks.size();
for(int i = 0;i<length;i++){
	String filename = blocks.get(i).text();
	String downloadUrl = blocks.get(i).child(0).attr("thumb");
}


最後使用Java的URL的讀取流寫入文件即完成下載

File f = new File("filename");	
FileOutputStream out = new FileOutputStream(f);
InputStream is = new URL(downloadUrl ).openStream();
byte[] buf = new byte[1024];
int len = 0;
while((len=is.read(buf))>0){
	out.write(buf, 0, len);
}
out.flush();
out.close();
is.close();


完整實現如下:

package jsoup;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Download {
	
	/**
	 * 
	 * @param pageURL	e.g. http://sc.chinaz.com/yinxiao/index_2.html
	 * @return 	true成功, false失敗
	 */
	public static boolean downloadYinXiao(String pageURL){
		System.out.println("任務開始<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		try {
			Map map = new HashMap();
			Document doc = Jsoup.connect(pageURL).get();
			System.out.println("Parse url:"+pageURL);
			System.out.println("title:"+doc.title());
			Element musicList = doc.getElementById("musiclist"); 
			if(musicList==null){
				System.out.println("Found node failed: musiclist");
				return false;
			}
			Elements blocks = musicList.getElementsByClass("music_block");
			int length = blocks.size();
			System.out.println("Found "+length+" yinxiao resources.");
			
			for(int i = 0;i> entrySet = map.entrySet();
			for(Entry o: entrySet){
				System.out.print("Download "+ o.getKey()+"...");
				boolean result = download(o.getKey(), o.getValue());
				if(result){
					System.out.println("OK.");
				}else{
					System.out.println("Failed. Url:"+o.getValue());
				}
			}
			System.out.println("下載完畢");
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>任務完畢");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("執行出錯");
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>任務失敗");
		}
		return false;
	}
	
	
	/**
	 * 取得文件擴展名
	 * @param str
	 * @return
	 */
	public static String getSuffix(String str){
		int lastDotIndex = str.lastIndexOf('.');
		if(lastDotIndex==-1){
			return ".mp3";
		}
		String suffix = str.substring(lastDotIndex);
		if(suffix.length()!=4){
			System.out.println("strange ext:" + suffix +" in " + str);
		}
		return suffix;
	}
	
	/**
	 * 
	 * @param filename  文件名
	 * @param url		 文件下載地址
	 * @return			 true下載成功,false下載失敗
	 */
	public static boolean download(String filename, String url){
		//默認把下載的文件保存在download文件夾下
		return download("download", filename, url);
	}
	/**
	 * 
	 * @param folder	文件保存的目錄
	 * @param filename	文件名
	 * @param url		文件下載地址
	 * @return			true下載成功,false下載失敗
	 */
	public static boolean download(String folder, String filename, String url){
		
		File dir = new File(folder);
		if(!dir.isDirectory()){
			dir.mkdirs();
		}
		
		File f = new File(dir, filename + getSuffix(url));
		try {
			FileOutputStream out = new FileOutputStream(f);
			InputStream is = new URL(url).openStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while((len=is.read(buf))>0){
				out.write(buf, 0, len);
			}
			out.flush();
			out.close();
			is.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 
	 * @param pageURL 	URL模版,需要替換的地方用一個問號代替
* e.g. http://sc.chinaz.com/yinxiao/index_?.html * @param min 代替問號的最小值 e.g. 2 * @param max 代替問號的最大值 e.g. 10 */ public static void batchDownloadYinXiao(String pageURL, int min, int max){ int i = 0; //最大出錯次數,達到則終止 int ERR_MAX_CNT = 10; int errCnt = 0; for(i=min;i<=max;i++){ String url = pageURL.replace("?", String.valueOf(i)); if(!downloadYinXiao(url)){ ++errCnt; } if(errCnt>=ERR_MAX_CNT){ System.out.println("自動停止。超過最大出錯次數:"+ERR_MAX_CNT+", 當前解析地址爲: "+url); return; } } System.out.println("批處理下載音效完畢。出錯次數: "+errCnt); } public static void main(String[] args) { // Download.downloadYinXiao("http://sc.chinaz.com/tag_yinxiao/LeQi.html"); Download.batchDownloadYinXiao("http://sc.chinaz.com/yinxiao/index_?.html", 1, 10); } }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章