概要
本文用于下载网易云音乐上特定歌手的歌曲和歌词
基于Java的爬虫方法
基于org.lib库爬取某歌手的前10的热歌的MP3及其歌词的代码如下:
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Cookie;
public class App {
public static void main(String[] args) throws Exception{
String artistId = "2116"; // 歌手ID,这里以陈奕迅为例,歌手id可以在网易云音乐上搜索歌手,进入歌手的主页,查看url中的id参数即为该歌手的id。
int numSongs = 10; // 下载歌曲数量
JSONArray songs;
songs = getArtistSongs(artistId); // 获取歌手的歌曲信息
// songs = getMusicInfo("断桥");
// System.out.println(songs);
if (songs != null) {
String saveDir = "Download"; // 保存目录
// 保存目录不存在则创建
if (!new java.io.File(saveDir).exists()) {
new java.io.File(saveDir).mkdirs();
}
for (int i = 0; i < songs.length() && i < numSongs; i++) {
JSONObject song = songs.getJSONObject(i);
String songName = song.getString("name"); // 歌曲名称
songName = new String(songName.getBytes("iso-8859-1"),"utf-8");
int songId = song.getInt("id"); // 歌曲ID
String songUrl = "https://music.163.com/song/media/outer/url?id=" + songId +
".mp3"; // 歌曲播放链接
System.out.println("歌曲名称:" + songName);
// System.out.println("Url下载:" + songUrl);
downloadSong(songName, songUrl, saveDir); // 下载歌曲
String lyric = getLyric(String.valueOf(songId)); // 获取歌词
if (lyric != null && !lyric.equals("")) {
FileOutputStream outputStream = new FileOutputStream(saveDir + "/" + songName + ".lrc");
outputStream.write(lyric.getBytes());
outputStream.close();
System.out.println("歌词下载完成!");
} else {
System.out.println("歌词下载失败!");
}
}
} else {
System.out.println("获取歌曲信息失败!"); // 如果获取歌曲信息失败
}
}
// 获取指定歌名的歌曲id
public static JSONArray getMusicInfo(String keyword) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--disable-gpu");
WebDriver driver = new ChromeDriver(chromeOptions);
// 添加Cookie
String url = "https://music.163.com/#/search/m/?s=" + keyword;
driver.get(url);
driver.switchTo().frame("g_iframe");
List<WebElement> dataAll = driver.findElements(By.xpath("//div[@class='item f-cb h-flag ']|//div[@class='item f-cb h-flag even ']"));
List<String> idList = new ArrayList<>();
List<String> nameList = new ArrayList<>();
List<String> authorList = new ArrayList<>();
for (WebElement data : dataAll) {
idList.add(data.findElement(By.xpath(".//div[@class='td w0']//a")).getAttribute("href").split("=")[1]);
nameList.add(data.findElement(By.xpath(".//div[@class='td w0']//b")).getAttribute("title"));
authorList.add(data.findElement(By.xpath(".//div[@class='td w1']//a")).getText());
}
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < idList.size(); i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", nameList.get(i));
jsonObject.put("author", authorList.get(i));
jsonObject.put("id", idList.get(i));
jsonArray.put(jsonObject);
}
driver.quit();
return jsonArray;
}
// 获取指定歌手的歌曲信息
public static JSONArray getArtistSongs(String artistId) {
String url = "https://music.163.com/api/v1/artist/songs?id=" + artistId + "&offset=0&total=true&limit=1000";
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// connection.setRequestMethod("GET");
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
connection.connect();
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
StringBuilder response = new StringBuilder();
int data;
while ((data = inputStream.read()) != -1) {
response.append((char) data);
}
// 打印
JSONObject jsonObject = new JSONObject(response.toString());
return jsonObject.getJSONArray("songs");
} else {
System.out.println("请求出错:" + connection.getResponseCode());
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 下载歌曲
public static void downloadSong(String songName, String songUrl, String saveDir) {
try {
URL url = new URL(songUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
connection.setInstanceFollowRedirects(false); // 允许重定向
connection.connect();
// 获取重定向后的URL
String redirectUrl = connection.getHeaderField("Location");
// System.out.println("重定向后的URL:" + redirectUrl);
connection = (HttpURLConnection) new URL(redirectUrl).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome//120.0.0.0 Safari/537.36");
connection.connect();
int responseCode = connection.getResponseCode();
System.out.println("响应码:" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(saveDir + "/" + songName + ".mp3");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
System.out.println(songName + " 下载完成!");
} else {
System.out.println(songName + " 下载失败,当前为VIP歌曲!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 下载歌词
public static String getLyric(String songId) {
String lyric = "";
try {
String url = "http://music.163.com/api/song/lyric?id=" + songId + "&lv=1&tv=-1";
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("user-agent", "Mozilla/5.0");
connection.setRequestProperty("Referer", "http://music.163.com");
connection.setRequestProperty("Host", "music.163.com");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
JSONObject jsonObject = new JSONObject(response.toString());
lyric = jsonObject.getJSONObject("lrc").getString("lyric");
} else {
System.out.println("Failed to fetch lyric, HTTP error code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
return lyric;
}
}
技术问题记录
- 获取MP3的连接在Python语言中可以直接得到真的URL,响应码200,在Java中报302,需要获得跳转地址。具体来说,在downloadSong方法中,代码对HTTP重定向做了处理,这是网易云音乐用于防止直接下载的一种方式。在下载歌词时,代码通过网易云音乐的API获取歌词信息。如果API发生变化,代码可能需要更新以适应新的API。
- 根据歌名获取ID功能尚未完全实现,需要登录账户才能搜索,易封号,尚未实现。
小结
本文用于下载网易云音乐上特定歌手的歌曲和歌词。这个程序大致做了以下几件事情:
- 定义了一个主类App,其中包含了main方法,是程序的入口点。
- 通过指定的歌手ID(这里使用了陈奕迅的ID作为例子),获取该歌手的歌曲信息列表。 设定了要下载的歌曲数量。
- 如果成功获取到歌曲信息,程序会创建一个目录用于保存下载的歌曲和歌词。
- 对于每首要下载的歌曲,程序会获取歌曲名、ID,并构造出歌曲的下载链接。 然后程序会尝试下载歌曲文件和对应的歌词。
- 如果下载成功,会在控制台打印相关信息,如歌曲名称、歌词下载状态等。 程序使用了几个关键方法来执行任务:
其中: - getArtistSongs(String artistId): 根据歌手ID获取歌手歌曲信息。
- downloadSong(String songName, String songUrl, String saveDir): 根据歌曲名、歌曲URL和保存目录下载歌曲。
- getLyric(String songId): 根据歌曲ID获取歌词。
- getMusicInfo(String keyword): 用Selenium WebDriver和Chrome浏览器(在无头模式下)获取指定关键词的歌曲信息,由于需要模拟登陆这在代码中被注释掉了。