从YouTube下载FLV格式视频
我其实不太明白YouTube是怎么提供视频的,但我一直在努力了解相关内容。
看起来以前的那个方法get_video现在已经过时了,不能再用了。有没有其他简单又符合Python风格的方法来获取YouTube视频呢?
3 个回答
4
我建议你自己写一个解析器,可以用urllib2或者Beautiful Soup这个工具。你可以查看DownThemAll的源代码,看看这个插件是怎么找到视频链接的。
6
这里有一个简单的Python脚本,可以用来下载YouTube视频。这个脚本没有复杂的功能,只是提取出需要的网址,然后访问一个特定的链接,最后把数据流保存到一个文件里:
import lxml.html
import re
import sys
import urllib
import urllib2
_RE_G204 = re.compile('"(http:.+.youtube.com.*\/generate_204[^"]+")', re.M)
_RE_URLS = re.compile('"fmt_url_map": "(\d*[^"]+)",.*', re.M)
def _fetch_url(url, ref=None, path=None):
opener = urllib2.build_opener()
headers = {}
if ref:
headers['Referer'] = ref
request = urllib2.Request(url, headers=headers)
handle = urllib2.urlopen(request)
if not path:
return handle.read()
sys.stdout.write('saving: ')
# Write result to file
with open(path, 'wb') as out:
while True:
part = handle.read(65536)
if not part:
break
out.write(part)
sys.stdout.write('.')
sys.stdout.flush()
sys.stdout.write('\nFinished.\n')
def _extract(html):
tree = lxml.html.fromstring(html)
res = {'204': _RE_G204.findall(html)[0].replace('\\', '')}
for script in tree.findall('.//script'):
text = script.text_content()
if 'fmt_url_map' not in text:
continue
# Found it. Extract the URLs we need
for tmp in _RE_URLS.findall(text)[0].split(','):
url_id, url = tmp.split('|')
res[url_id] = url.replace('\\', '')
break
return res
def main():
target = sys.argv[1]
dest = sys.argv[2]
html = _fetch_url(target)
res = dict(_extract(html))
# Hit the 'generate_204' URL first and remove it
_fetch_url(res['204'], ref=target)
del res['204']
# Download the video. Now I grab the first 'download' URL and use it.
first = res.values()[0]
_fetch_url(first, ref=target, path=dest)
if __name__ == '__main__':
main()
运行这个脚本的方法:
python youdown.py 'http://www.youtube.com/watch?v=Je_iqbgGXFw' stevegadd.flv
saving: ........................... finished.
15
你可以试试 youtube-dl 这个工具。
http://rg3.github.com/youtube-dl/documentation.html
我不太确定有没有好的接口,但它是用 Python 写的,所以理论上你可以做得比 Popen 更好一点 :)