Created
May 31, 2015 15:28
-
-
Save itkq/36bfb9986fca0d4122db to your computer and use it in GitHub Desktop.
Niconico downloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'niconico' | |
require 'mechanize' | |
require 'benchmark' | |
require 'dotenv' | |
class NicoDown | |
def initialize | |
Dotenv.load | |
@nico = Niconico.new(ENV['NICO_USER'], ENV['NICO_PASS']) | |
@mech = Mechanize.new | |
@format = '.mp4' | |
@dir = './downloads/' | |
puts 'logining ... ' | |
login_url = 'https://secure.nicovideo.jp/secure/login?site=niconico' | |
@mech.post(login_url, 'mail' => ENV['NICO_USER'], 'password' => ENV['NICO_PASS']) | |
puts 'mechanize logined.' | |
@nico.login | |
puts 'niconico logined.' | |
end | |
# search result url | |
def download_videos url | |
puts '[download videos from search result url]' | |
@mech.get url | |
loop do | |
next_page = @mech.page.link_with(:text => "次へ >") | |
doc = Nokogiri::HTML(@mech.page.body) | |
(doc/'.item_right'/'h6'/'a').each do |a| | |
href = a.attribute('href').value | |
begin | |
@mech.get href | |
target = @mech.page.body.scan(/so\d+/).first || @mech.page.body.scan(/sm\d+/).first | |
puts "target: #{href} ==> #{target}" | |
get_video(target) | |
rescue | |
puts 'failed.' | |
end | |
end | |
break if next_page | |
puts "==> next page" | |
next_page.click | |
end | |
puts 'finished.' | |
end | |
def download_latest_video url | |
puts '[download lastest video]' | |
begin | |
@mech.get url | |
doc = Nokogiri::HTML(@mech.page.body) | |
href = (doc/'.item_right'/'h6'/'a').first.attribute('href').value | |
@mech.get href | |
target = @mech.page.body.scan(/so\d+/).first || @mech.page.body.scan(/sm\d+/).first | |
get_video(target) | |
rescue => e | |
puts e.message | |
end | |
end | |
def get_target target_url | |
@mech.get target_url | |
ret = @mech.page.body.scan(/so\d+/).first || @mech.page.body.scan(/sm\d+/).first | |
puts "target ==> #{ret}" | |
get_video ret | |
end | |
# sm\d+, or so\d+ | |
def get_video target | |
video = @nico.video(target) | |
print "downloading [#{video.title}] ... " | |
result = Benchmark.realtime do | |
open("#{@dir}#{video.title}#{@format}", "w") do |f| | |
f.write video.get_video | |
end | |
end | |
puts "completed. (#{result}[s])" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment