2008年9月3日 星期三

根據 ID 抓取 YouTube 影片


def progress_hook(block_number, block_size, total_size):
if total_size > 0:
percentage = 100 * block_number * block_size / total_size
if percentage > 100:
percentage = 100
print '%2d%%' % percentage

def getYouTubeVideoByID(video_id, output_filename):
import re, urllib
url = 'http://www.youtube.com/v/%s' % (video_id)
real_url = urllib.urlopen(url).geturl()
match = re.findall("t=([^&]*)", real_url)
if match:
fetch_url = 'http://www.youtube.com/get_video.php?video_id=%s&t=%s' % (video_id, match[0])
print fetch_url
try:
urllib.urlretrieve(fetch_url, output_filename, progress_hook)
except urllib.ContentTooShortError:
print 'ContentTooShortError'


其中 progress_hook 是用來顯示進度的,如果不喜歡可以自己修改格式,或是在 getYouTubeVideoByID 裡面呼叫 urllib.urlretrieve 的地方把 progress_hook 這個參數拿掉。

使用方法: getYouTubeVideoByID(<id>, <file_name>)
範例:
getYouTubeVideoByID('2scOjA_U09w', 'E:\\CCF.flv')

0 意見: