hakeの日記

Windows環境でプログラミングの勉強をしています。

ニコニコ動画の検索

nicovedeoライブラリを使って検索させてみました。たまに文字化けするのはSJIS環境で実行しているせいでしょうか(^^ゞ
ザウルス用にqrtubeのニコ動版を作ってみようかなぁとも思ったのですけどmplayerで再生できないんですね、残念。



初音ミク」で検索した3ページ目

http://www.nicovideo.jp/watch/sm2084745
sm2084745
【初音ミク】サイハテ本家PV+ピアノver.
サイハテ本家PVにピアノver.を合わせてみました。やはり、この歌にはPVも必須だと思いましたので、動画...
2min 46sec
-----
http://www.nicovideo.jp/watch/sm2084815
sm2084815
初音ミク「君の瞳に恋してる」(引退記念)
おっちゃんは疲れました。いくらがんばってもおっちゃんちのミクはかわいく上手に唄ってくれません。ミ...
3min 45sec
-----
http://www.nicovideo.jp/watch/sm2084596
sm2084596
鏡音リン・レン×初音ミク×angela(atsuko) で『Shangri-La』
XPのWindowsMovieMakerで作成してみました。(前半多少音ズレしてますorz)鏡音リン・レン×初音ミク×ange...
5min 1sec
-----
以下略


久しぶりにHpricotを使うとわけわかりませんw

#require 'rubygems'
require 'nicovideo'
require 'yaml'
require 'kconv'


class MyBase < Nicovideo::Base
  def initialize(mail, password)
    super
  end

  def get_html(url)
    @agent.get_file(url)
  end
end


class NicoData
  attr_accessor :url, :id, :title, :comment, :time
  def initialize
    @url     = ""
    @id      = ""
    @title   = ""
    @comment = ""
    @time    = ""
  end
end



def search_word(nv, word, page)
  keyword = ""
  word.toutf8.unpack("H*").to_s.upcase.gsub(/(..)/) do |hex|
    keyword += "%#{hex}"
  end

  html = nv.get_html("http://www.nicovideo.jp/search/#{keyword}?page=#{page}")
  items = Array.new

  doc  = Hpricot(html)
  divs = (doc/:html/:body/"div.thumb_R")
  divs.each do |div|
    item = NicoData.new

    a = div.at("a")
    url = a["href"]
    /^.+\/(sm\d+)/ =~ url
    id = $1
    title = a.inner_text.tosjis
    p = div.at("p")
    comment = p.inner_text.split(/\n/)[1].tosjis

    item.url = url
    item.id  = id
    item.title = title
    item.comment = comment

    items.push item
  end

  divs = (doc/:html/:body/"div.thumb_L")
  i = 0
  divs.each do |div|
    str = div.at("p").at("strong")
    time = str.inner_text.tosjis
    time.sub!(//, "min ").sub!(//, "sec")
    items[i].time = time
    i += 1
  end
  return items
end


##########
# 
# MAIN
#
##########

WORD = '初音ミク'
PAGE = 3

# set account
account = YAML.load_file('account.yml')
mail = account['mail']
password = account['password']

# you must login to Nicovideo
nv = MyBase.new(mail, password)
nv.login

items = search_word(nv, WORD, PAGE)

if items.size == 0
  puts "No Item"
else
  items.each do |item|
    puts item.url
    puts item.id
    puts item.title
    puts item.comment
    puts item.time
    puts '-----'
  end
end