是否有人有必要更正以下程序,以便从html结果中获取YouTube视频ID。
这是我在Playing youtube music from the command line创建的ruby代码。我正试着让它在我的电脑上运行:
require 'hpricot'
require 'open-uri'
playlist=Array.new
#This thread actually plays the tracks in the playlist then removes them.
player=Thread.new {
while true
#If the playlist is empty, play random mp3s until someone adds something
if playlist.length==0 then
system('./random_music.sh')
else
system('mpg321 -q '+playlist.shift)
end
end
}
#While the main thread handles the user interface:
while true
puts "What would you like to listen to?"
search_string= gets.chomp
puts"Searching for #{search_string}..."
#Use Hpricot to load the youtube search page and scrape the titles and ids of the top 5 results
doc = Hpricot(open("https://www.youtube.com/results?search_type=search_videos&search_query="+search_string.gsub(' ','+')))
result_divs=doc.search("div[@id=search-results]/div")
results=Array.new
#Ask the user which one they want
for i in 0..4 do
#keep the a object as it has both bits of data
results[i]=result_divs[i].search("div.result-item-main-content/h3/a")
puts (i+1).to_s + ') ' + results[i].inner_html
end
choice=gets.chomp.to_i
if (1..5).include?(choice) then
choice-=1
youtube_id = results[choice].attr('href').split('&')[0].split('=')[1]
#Download/extract the audio in parallel so that more tracks can be added in the meantime
Thread.new(youtube_id,results[choice].inner_html) { |id,title|
if ! File.exist?(id+'.mp3')
puts 'Downloading ' + title
system('youtube-dl --extract-audio -w -q -f 5 --no-part '+id)
end
playlist<<id +'.mp3'
puts title+' added to playlist'
}
end
end