Java爬取并下載酷狗音樂

本文方法及代碼僅供學習,僅供學習。

案例:

  下載酷狗TOP500歌曲,代碼用到的代碼庫包含:Jsoup、HttpClient、fastJson等。

正文:

  1、分析是否可以獲取到TOP500歌單

打開酷狗首頁,查看TOP500,發現存在分頁,每頁顯示22條歌曲,

發現酷狗的鏈接如下:

https://www.kugou.com/yy/rank/home/1-8888.html?from=homepage

通過更改鏈接中的1可以進行分頁,所以我們可以通過更改鏈接地址獲取其余的歌曲。

2、分析找到正真的mp3下載地址

?點一個歌曲進入播放頁面,使用谷歌瀏覽器的控制臺的Elements,搜一下mp3,很輕松就定位到了MP3的位置。

但是使用java訪問的時候爬取的html里卻沒有該mp3的文件地址,那么這肯定是在該頁面的位置使用了js來加載mp3,那么刷新下網頁,看網頁加載了哪些東西,加載的東西有點多,著重看一下js、php的請求,主要是看里面有沒有mp3的地址。

最終在列表中找到:

https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery191044492686523157987_1559446927765&hash=458E9B9F362277AC37E9EEF1CB80B535&album_id=18712576&dfid=1ZxQbe0MiP8J09j5tR0Np9IA&mid=9393340fecff864a4d6c4e95099b2be1&platid=4&_=1559446927766

這個請求結果中發現了mp3的完整地址:

那這個js是怎么判斷是哪首歌的呢,那么只可能是hash這個參數來決定歌曲的,然后到播放頁面里找到這個hash的位置,是在下面的js里:

var dataFromSmarty = [{"hash":"667939C6E784265D541DEEE65AE4F2F8","timelength":"237051","audio_name":"\u767d\u5c0f\u767d - \u6700\u7f8e\u5a5a\u793c","author_name":"\u767d\u5c0f\u767d","song_name":"\u6700\u7f8e\u5a5a\u793c","album_id":0}],//當前頁面歌曲信息playType = "search_single";//當前播放</script>

在去java爬取該網頁,查看能否爬到這個hash,果然,爬取的html里有這段js,到現在mp3的地址也找到了,歌單也找到了,那么下一步就用程序實現就可以了。

3、代碼實現

SpiderKugou.java
package com.billy.test;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** 爬取并下載酷狗的歌曲*/
public class SpiderKugou {private static String filePath;//酷狗地址private static String LINK;//mp3地址private static String mp3;static {filePath = "F:/music/";LINK = "https://www.kugou.com/yy/rank/home/PAGE-8888.html?from=rank";mp3 = "https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19103632090130122796_1558800325111&"+ "hash=HASH&_=TIME";}public static void main(String[] args) throws Exception {for(int i = 5 ; i < 23 ; i++){String url = LINK.replace("PAGE", i + "");downSong(url);}}/*** 下載歌曲* @param url* @throws Exception*/private static void downSong(String url) throws Exception{HttpGetConnect connect = new HttpGetConnect();String content = connect.connect(url, "utf-8");HtmlManage html = new HtmlManage();Document doc = html.manage(content);Element ele = doc.getElementsByClass("pc_temp_songlist").get(0);Elements elements = ele.getElementsByTag("li");for(int i = 0 ; i < elements.size() ; i++){Element item = elements.get(i);String title = item.attr("title").trim();String link = item.getElementsByTag("a").first().attr("href");downLoad(link,title);Thread.sleep(1000);}}/*** 下載* @param url* @param name* @throws IOException*/private static void downLoad(String url,String name) throws IOException{String hash = "";HttpGetConnect connect = new HttpGetConnect();String content = connect.connect(url, "utf-8");String regEx = "\"hash\":\"[0-9A-Z]+\"";// 編譯正則表達式Pattern pattern = Pattern.compile(regEx);Matcher matcher = pattern.matcher(content);if (matcher.find()) {hash = matcher.group();hash = hash.replace("\"hash\":\"", "");hash = hash.replace("\"", "");}String item = mp3.replace("HASH", hash);item = item.replace("TIME", System.currentTimeMillis() + "");System.out.println("item:" + item);String mp = connect.connect(item, "utf-8");mp = mp.substring(mp.indexOf("(") + 1, mp.length() - 3);JSONObject json = JSON.parseObject(mp);if(Integer.parseInt(json.get("status") + "") != 0){String playUrl = json.getJSONObject("data").getString("play_url");FileDownload down = new FileDownload();down.download(playUrl, filePath + name + ".mp3");}}}
View Code
HttpGetConnect.java
package com.billy.test;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;/*** httpclient 工具類*/
public class HttpGetConnect {/***  獲取html內容* @param url* @param charsetName  UTF-8、GB2312* @return* @throws IOException*/public static String connect(String url,String charsetName) throws IOException{BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).build();String content = "";try{HttpGet httpget = new HttpGet(url);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(50000).setConnectionRequestTimeout(50000).build();httpget.setConfig(requestConfig);httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");httpget.setHeader("Accept-Encoding", "gzip,deflate,sdch");httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");httpget.setHeader("Connection", "keep-alive");httpget.setHeader("Upgrade-Insecure-Requests", "1");httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");httpget.setHeader("cache-control", "max-age=0");httpget.setHeader("Referer","https://www.kugou.com/song/");//設置cookiehttpget.setHeader("Cookie", "kg_mid=9393340fecff864a4d6c4e95099b2be1;");CloseableHttpResponse response = httpclient.execute(httpget);int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();InputStream instream = entity.getContent();BufferedReader br = new BufferedReader(new InputStreamReader(instream,charsetName));StringBuffer sbf = new StringBuffer();String line = null;while ((line = br.readLine()) != null){sbf.append(line + "\n");}br.close();content = sbf.toString();} else {content = "";}}catch(Exception e){e.printStackTrace();}finally{httpclient.close();}log.info("content is " + content);return content;}private static Log log = LogFactory.getLog(HttpGetConnect.class);
}
View Code
HtmlManage.java
package com.billy.test;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** html manage 工具類*/
public class HtmlManage {public Document manage(String html) {Document doc = Jsoup.parse(html);return doc;}public Document manageDirect(String url) throws IOException {Document doc = Jsoup.connect(url).get();return doc;}public List<String> manageHtmlTag(Document doc, String tag) {List<String> list = new ArrayList<String>();Elements elements = doc.getElementsByTag(tag);for (int i = 0; i < elements.size(); i++) {String str = elements.get(i).html();list.add(str);}return list;}public List<String> manageHtmlClass(Document doc, String clas) {List<String> list = new ArrayList<String>();Elements elements = doc.getElementsByClass(clas);for (int i = 0; i < elements.size(); i++) {String str = elements.get(i).html();list.add(str);}return list;}public List<String> manageHtmlKey(Document doc, String key, String value) {List<String> list = new ArrayList<String>();Elements elements = doc.getElementsByAttributeValue(key, value);for (int i = 0; i < elements.size(); i++) {String str = elements.get(i).html();list.add(str);}return list;}private static Log log = LogFactory.getLog(HtmlManage.class);
}
View Code
FileDownload.java
package com.billy.test;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;/*** 文件下載工具類*/
public class FileDownload {/*** 文件下載** @param url  鏈接地址* @param path 要保存的路徑及文件名* @return*/public static boolean download(String url, String path) {boolean flag = false;CloseableHttpClient httpclient = HttpClients.createDefault();RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();HttpGet get = new HttpGet(url);get.setConfig(requestConfig);BufferedInputStream in = null;BufferedOutputStream out = null;try {for (int i = 0; i < 3; i++) {CloseableHttpResponse result = httpclient.execute(get);System.out.println(result.getStatusLine());if (result.getStatusLine().getStatusCode() == 200) {in = new BufferedInputStream(result.getEntity().getContent());File file = new File(path);out = new BufferedOutputStream(new FileOutputStream(file));byte[] buffer = new byte[1024];int len = -1;while ((len = in.read(buffer, 0, 1024)) > -1) {out.write(buffer, 0, len);}flag = true;break;} else if (result.getStatusLine().getStatusCode() == 500) {continue;}}} catch (Exception e) {e.printStackTrace();flag = false;} finally {get.releaseConnection();try {if (in != null) {in.close();}if (out != null) {out.close();}} catch (Exception e) {e.printStackTrace();flag = false;}}return flag;}private static Log log = LogFactory.getLog(FileDownload.class);
}
View Code

?

?
?
?
?

?

轉載于:https://www.cnblogs.com/BillyYoung/p/10962441.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/248820.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/248820.shtml
英文地址,請注明出處:http://en.pswp.cn/news/248820.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C 表達式及返回值

以下程序的輸出結果是__A____。 #include<stdio.h> main() {int i10,j10;printf("%d,%d\n",i,j--); } A、11,10 B、9,10 C、010,9 D、10,9 8.若變量a、i已正確定義&#xff0c;且i已正確賦值&#xff0c;合法的語句是___B___。 A、a1 B、i; C、…

Webpack/Vue-cli兩種方式加載markdown文件并實現代碼高亮

準備的資源&#xff1a; highlight.js &#xff1a; 實現代碼高亮&#xff0c;通過npm install highlight.js -D安裝 vue-markdown-loader&#xff1a;解析md文件的必備loader&#xff0c;通過npm install vue-markdown-loader -D安裝 下面我們分兩個場景來說明一下md文件的…

新浪微博第三方登陸重定向錯誤23123

新浪微博第三方登陸重定向錯誤23123 2019年06月02日 13:49:43 溫室花朵 閱讀數&#xff1a;2更多 個人分類&#xff1a; 第三方微博登陸21323編輯當我們使用微博第三方登陸的時候&#xff0c;發現登陸出錯了&#xff0c;錯誤碼為&#xff1a;21323&#xff0c;解決方案如下&…

Utility Manager 的一些百度不了的操作

一進來是不是這樣的&#xff01; 那突然出了點問題&#xff0c;咋辦呢&#xff01; 就像這樣子的&#xff0c; 恢復默認布局就OK啦&#xff01;哈哈哈&#xff0c;太聰明啦&#xff0c;但是百度了好長時間還是找不到啊&#xff0c;怎么辦吶&#xff0c;煩死啦&#xff01; 其實…

Echart 5.0+版本報錯Error in data(): “TypeError: Cannot read properties of undefined (reading ‘graphic‘)“

首先第一步需要檢查echarts的導入方式&#xff0c;在5.0以后的版本&#xff0c;echarts做了比較大的調整&#xff0c;在vue中引入時必須使用如下命令 // import echarts from echarts 這種方式高版本不支持import * as echarts from echartsvue.prototype.$echarts echarts其次…

記錄一次內網滲透試驗

0x00 前言 目標&#xff1a;給了一個目標機ip&#xff0c;要求得到該服務器權限&#xff0c;并通過該ip滲透至內網控制內網的兩臺服務器 攻擊機&#xff1a;kali (192.168.31.51) 目標機&#xff1a;windows 2003 (192.168.31.196) 0x01 信息收集 nmap端口探測 御劍后臺掃描 …

2018-2019 1 20165203 實驗五 通用協議設計

2018-2019 1 20165203 實驗五 通用協議設計 OpenSSL學習 定義&#xff1a;OpenSSL是為網絡通信提供安全及數據完整性的一種安全協議&#xff0c;囊括了主要的密碼算法、常用的密鑰和證書封裝管理功能以及SSL協議&#xff0c;并提供了豐富的應用程序供測試或其它目的使用。基本功…

弄懂webpack,只要看這一片就夠了(文末有福利)

什么是webpack ? webpack是什么&#xff0c;官網中是這么說的。 ? 本質上&#xff0c;webpack 是一個現代 JavaScript 應用程序的靜態模塊打包器(module bundler)。當 webpack 處理應用程序時&#xff0c;它會遞歸地構建一個依賴關系圖(dependency graph)&#xff0c;其中包…

beta沖刺總結那周余嘉熊掌將得隊

作業格式 課程名稱&#xff1a;軟件工程1916|W&#xff08;福州大學&#xff09;作業要求&#xff1a;項目Beta沖刺團隊名稱&#xff1a; 那周余嘉熊掌將得隊作業目標&#xff1a;beta沖刺總結隊員學號隊員姓名博客地址備注221600131Jaminhttps://www.cnblogs.com/JaminWu/隊長…

在Winform中菜單動態添加“最近使用文件”

最近在做文件處理系統中&#xff0c;要把最近打開文件顯示出來&#xff0c;方便用戶使用。網上資料有說&#xff0c;去遍歷“C:\Documents and Settings\Administrator\Recent”下的最近文檔本。文主要介紹在Winform界面菜單中實現【最近使用的文件】動態菜單的處理&#xff0c…

Vue組件通信原理剖析(一)事件總線的基石 $on和$emit

首先我們先從一個面試題入手。 面試官問&#xff1a; “Vue中組件通信的常用方式有哪些&#xff1f;” 我答&#xff1a; 1. props 2. 自定義事件 3. eventbus 4. vuex 5. 還有常見的邊界情況$parent、$children、$root、$refs、provide/inject 6. 此外還有一些非props特性$att…

display:flex彈性布局

一、背景 前段時間幫公司運維小姑娘調整她自己寫的頁面樣式時發現她用了display: flex&#xff0c;我這個后端老古董還不太懂flex&#xff0c;自愧不如啊&#xff0c;所以寫篇博客記錄學習下。 現在寫的前端頁面還停留在依賴 display 屬性 position屬性 float屬性的布局方式&…

一些好的思維方式

定理s 一、墨菲定律 觀點&#xff1a;1.任何事都沒有表面看起來那么簡單&#xff1b;2.所有的事都會比你預計的時間長&#xff1b;3.會出錯的事總會出錯&#xff1b;4.如果你擔心某種情況發生&#xff0c;那么它就更有可能發生。 墨菲定律的核心觀點就4點&#xff0c;不算復雜&…

Vue組件通信原理剖析(二)全局狀態管理Vuex

首先我們先從一個面試題入手。 面試官問&#xff1a; “Vue中組件通信的常用方式有哪些&#xff1f;” 我答&#xff1a; 1. props 2. 自定義事件 3. eventbus 4. vuex 5. 還有常見的邊界情況$parent、$children、$root、$refs、provide/inject 6. 此外還有一些非props特性$att…

初識單點登錄及JWT實現

單點登錄 多系統&#xff0c;單一位置登錄&#xff0c;實現多系統同時登錄的一種技術 &#xff08;三方登錄&#xff1a;某系統使用其他系統的用戶&#xff0c;實現本系統登錄的方式。如微信登錄、支付寶登錄&#xff09; 單點登錄一般是用于互相授信的系統&#xff0c;實現單一…

Vue組件通信原理剖析(三)provide/inject原理分析

首先我們先從一個面試題入手。 面試官問&#xff1a; “Vue中組件通信的常用方式有哪些&#xff1f;” 我答&#xff1a; 1. props 2. 自定義事件 3. eventbus 4. vuex 5. 還有常見的邊界情況$parent、$children、$root、$refs、provide/inject 6. 此外還有一些非props特性$att…

iMX6開發板-uboot-網絡設置和測試

本文章基于迅為IMX6開發板 將iMX6開發板通過網線連接到路由器&#xff0c;同時連接好調試串口&#xff0c;上電立即按 enter&#xff0c;即可進入 uboot。然后輸入命令 pri&#xff0c;查看開發板當前的配置&#xff0c;如下圖所示可以看到 ip 地址、子網掩碼 等信息。 本文檔測…

Django ajax 檢測用戶名是否已被注冊

添加一個 register.html 頁面 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title> </head> <body> <form><p>用戶名<input id"username" type&…

pyqt5控件

背景色設置 self.tab.setStyleSheet("background: rgb(238, 233, 233)") self.but_0.setStyleSheet("background: rgb(0, 255, 255)")樣式&#xff1a; self.but_0.setStyle(QStyleFactory.create("Windows"))字體&#xff1a; self.lineEdit.se…

詳解JDBC連接數據庫

一、概念 1. 為了能讓程序操作數據庫&#xff0c;對數據庫中的表進行操作&#xff0c;每一種數據庫都會提供一套連接和操作該數據庫的驅動&#xff0c;而且每種數據庫的驅動都各不相同&#xff0c;例如mysql數據庫使用mysql驅動&#xff0c;oracle數據庫使用oracle驅動&#xf…