【发布时间】:2011-05-16 07:45:23
【问题描述】:
我无法真正理解 youtube 是如何提供视频的,但我一直在阅读我所能阅读的内容,似乎旧方法 get_video 现在已经过时并且不能再使用了,因此我想问是否还有其他方法pythonic和简单的方法来收集youtube视频。
【问题讨论】:
标签: python download youtube urllib2
我无法真正理解 youtube 是如何提供视频的,但我一直在阅读我所能阅读的内容,似乎旧方法 get_video 现在已经过时并且不能再使用了,因此我想问是否还有其他方法pythonic和简单的方法来收集youtube视频。
【问题讨论】:
标签: python download youtube urllib2
你可能对 youtube-dl 有一些运气
http://rg3.github.com/youtube-dl/documentation.html
我不确定是否有好的 API,但它是用 Python 编写的,所以理论上你可以做一些比 Popen 更好的事情:)
【讨论】:
这是一个用于下载 Youtube 视频的快速 Python 脚本。没有花里胡哨,只需刮出必要的 url,点击 generate_204 url,然后将数据流式传输到文件:
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.
【讨论】:
python 3.3.0。它给出了很多错误。无论如何,你能解释一下这个想法,以便我可以自己重写吗? generate_204 url 是什么? “点击 generate_204 url 然后将数据流式传输到文件”是什么意思?
我建议使用 urllib2 或 beautifulsoup 编写自己的解析器。您可以查看DownThemAll 的源代码,了解该插件如何找到视频网址
【讨论】: