B站,N站,湯站,爬蟲下載資源總結與技巧(二)

前言

  • 這篇是上篇的後續,主要是編寫一個簡單的http下載工具,使用的wget庫,這周就簡單寫一寫,下幾週會重點說說,真實下載處理及查表優化。

注意

  • 對於網絡下載,cdn下載等等,要主要請求頭的一些配置,並處理好超時問題。
  • B站須要配置,"Referer", "http://www.bilibili.com/"
  • N站,須要注意的是舊資源重複問題。
  • Tumblr站,暫時無遇到特別注意的地方。

代碼

pom配置

<dependency>
			<groupId>com.github.axet</groupId>
			<artifactId>wget</artifactId>
			<version>1.4.9</version>
		</dependency>

通用下載工具

//下載文件
    public static String downToLocal(String url,String fileBasePath, String fileName, String extName, JSONObject headers) throws Exception {

        Logger logger = LoggerFactory.getLogger(DownloadFileTool.class);

        String name = (fileName + "." + extName).toLowerCase();
        String filePath = fileBasePath + name;

        String downUrl = url;
        File file = new File(filePath);


        try {
            URL downUrll = new URL(downUrl);
            DownloadInfo info = new DownloadInfo(downUrll);
            info.setUserAgent("Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
            if (headers != null) {
                info.setReferer(new URL(headers.get("Referer").toString()));
            }
            WGet get = new WGet(info, file);
            get.download();
            String newUrl = name;
            //logger.info("downToLocal baseUrl:" + url  +  " newUrl:" + newUrl +  " fileName:" + name + " filePath:" + filePath);
            return newUrl;
        }
        catch (Exception e){
            file.delete();
            throw e;
        }
    }

原文:http://raychow.linkfun.top/2017/12/22/archives/9_javaSpring/spriderDownloadTool/index/java

相關文章
相關標籤/搜索