Created
February 18, 2013 13:15
-
-
Save satomacoto/4977284 to your computer and use it in GitHub Desktop.
Get youtube links from a web site
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'open-uri' | |
require 'kconv' | |
require 'nokogiri' | |
require 'json' | |
class Youtubelinks | |
def videoid(id) | |
url = "https://gdata.youtube.com/feeds/api/videos/#{id}?v=2&alt=json" | |
begin | |
JSON.parse(open(url).read) | |
rescue OpenURI::HTTPError => e | |
p e | |
nil | |
rescue => e | |
p e | |
nil | |
end | |
end | |
def extract(url) | |
res = {} | |
begin | |
doc = Nokogiri::HTML(open(url.strip, "r:binary").read.toutf8) | |
res[:url] = url.strip | |
res[:title] = (doc/:title).text | |
res[:videoids] = [] | |
patterns = [ | |
[:embed, [ | |
[:src, /v\/([-\w]+)/] | |
] | |
], | |
[:iframe, [ | |
[:src, /youtube.com\/embed\/([-\w]+)/] | |
] | |
], | |
[:a, [ | |
[:href, /youtube.com\/watch\?v=([-\w]+)/], | |
[:href, /youtu\.be\/([-\w]+)/]] | |
] | |
] | |
patterns.each do |tag, attrs| | |
(doc/tag).each do |elem| | |
attrs.each do |attr, pat| | |
elem[attr] =~ pat | |
if $1 | |
res[:videoids] << $1 | |
end | |
end | |
end | |
end | |
res[:videoids].uniq! | |
rescue => err | |
p err | |
res = nil | |
end | |
return res | |
end | |
end | |
@yt = Youtubelinks.new | |
yt = @yt.extract("http://matome.naver.jp/odai/2135486241817549301") | |
videoid = yt[:videoids][0] | |
p @yt.videoid(videoid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment