Mechanizeを使う

youtubeから検索語句に対するタイトルとアドレスをとってくる。

# -*- coding: utf-8 -*-

require 'mechanize'
require 'nokogiri'

puts "youtubeから動画を検索してURLを返します。"
puts "検索したい語を入力してください。:"
line = gets

agent = Mechanize.new
agent.get("http://www.youtube.com/")
agent.page.form_with(:action => "/results"){ |form|
  form.field_with(:name =>"search_query").value = line.toutf8()
  form.click_button
}

output = {}

agent.page.links_with(:href => /\/watch\?v\=/ , :class => "yt-uix-tile-link" ).each do |link|
  movieurl = link.href
  movieurl = movieurl.split("watch?v=").last
  movieurl = movieurl.split("&feature").first
  output[link.text] = movieurl 
end 

puts output
fout = File.open("title.txt","w")
fout.write(output)