Skip to content

Instantly share code, notes, and snippets.

@bczhc
Created September 7, 2022 09:50
Show Gist options
  • Select an option

  • Save bczhc/fea67cd7f2c1e806f5118792958e64bf to your computer and use it in GitHub Desktop.

Select an option

Save bczhc/fea67cd7f2c1e806f5118792958e64bf to your computer and use it in GitHub Desktop.
网易云音乐获取歌单列表

需要填充:HEADERSPLAYLIST_ID

#!/usr/bin/env ruby
require 'nokogiri'
require 'open-uri'
require 'net/http'
require 'json'
HEADERS = %{XX
XX
}
PLAYLIST_ID = XX
def request_url(id) = "https://music.163.com/playlist?id=#{id}"
def fetch_playlist(playlist_id)
uri = URI(request_url(playlist_id))
req = Net::HTTP::Get.new(uri)
HEADERS.each_line(chomp: true) do |line|
index = line.index(': ')
key = line[0...index]
value = line[(index + 2)..]
req[key] = value
end
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http|
http.request(req)
}
fail if res == nil
body = res.body
fail if body == nil
doc = Nokogiri::HTML(body)
titles = doc.xpath(%{//div[@id='song-list-pre-cache']//ul[@class='f-hide']/li/a/text()}).map do |x|
fail if x.content.match /\n/
x.content
end
ids = doc.xpath(%{//div[@id='song-list-pre-cache']//ul[@class='f-hide']/li/a/@href}).map do |url|
# @type [String]
url = url.content
arr = url.scan(/^\/song\?id=([0-9]*)$/)
arr[0][0]
end
# @type [Array<Array<Integer, String>>]
list = ids.map { |x| x.to_i }.zip(titles)
list.map { |x| Song.new(x[0], x[1]) }
end
class Song
attr_accessor :id, :name
def initialize(id, name)
@id = id
@name = name
end
def to_json(*args)
{
'id' => @id,
'name' => @name,
}.to_json(args)
end
end
list = fetch_playlist(PLAYLIST_ID)
puts list.to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment