如何使用youtube_it gem for Ruby on Rails从youtube频道(https://www.youtube.com/channel/UCwHnsUEYrQUTUxC4dvrv0QQ)获取视频?
或者你能告诉我另一个可以帮助我的宝石吗?
答案 0 :(得分:1)
我就是这样做的。
我在config / initializers / youtube_it.rb中有这个:
$youtube_it = YouTubeIt::Client.new(dev_key: ENV['YOUTUBE_KEY'])
获取视频的第一页:
query = {
author: channel_url.split('/').last,
order_by: 'published',
page: 1,
}
# scraping from newesr to oldest
videos = $youtube_it.videos_by(query).videos
这是一个刮擦的例子,你可以安排一个工作来定期调用scrape方法。
该方法首先从最新视频到最旧视频。然后backward_scrape_done
设置为true
,然后仅抓取新视频。
class Import < ActiveRecord::Base
def scrape
query = {
author: channel_url.split('/').last,
order_by: 'published',
}
query[:page] = cursor
# scraping from newesr to oldest
videos = fetch_videos(query)
if videos.count == 0
# we've reached the end
self.backward_scrape_done = true
self.cursor = 0
end
for video in videos
add_video video
end
# next time scrape next page
self.cursor = cursor + 1
ensure
self.scraped_at = Time.now
self.save!
end
def fetch_videos(query)
$youtube_it.videos_by(query).videos
end
def add_video video
url = video.player_url.
gsub(/[?&]feature=youtube_gdata_player/, '')
# skip this video if its already there
if Video.where(youtube_url: url).first
self.cursor = 0
save
return
end
video = YoutubeVideo.create!(
title: video.title,
duration: video.duration,
description: video.description,
youtube_url: url,
)
end
end
希望有所帮助!
更新:由于youtube很快就会摆脱它的API V2,你应该切换到支持最新API的东西,比如我现在使用的yt
gem: