使用Python从.swf提取视频
我写了一段代码,用来生成视频链接,比如下面这个链接。拿到链接后,我尝试用这种方式下载视频:
import urllib.request
import os
url = 'http://www.videodetective.net/flash/players/?customerid=300120&playerid=351&publishedid=319113&playlistid=0&videokbrate=750&sub=RTO&pversion=5.2%22%20width=%22670%22%20height=%22360%22'
response = urllib.request.urlopen(url).read()
outpath = os.path.join(os.getcwd(), 'video.mp4')
videofile = open(outpath , 'wb')
videofile.write(response)
videofile.close()
但是我得到的只是一个58KB的文件,里面的内容无法读取。有人能告诉我该怎么做吗?
1 个回答
17
你的代码并不是在下载编码后的视频文件,而是下载了一个用于播放视频的Flash应用程序(CWS格式)。这个应用程序在浏览器中运行,会动态加载并播放视频。要找到实际的视频源,你需要进行一些逆向工程。以下是我尝试的方法:
解压SWF文件
首先,把你提到的58K文件保存在你的硬盘上,命名为 test.swf
(或者类似的名字)。然后,你可以使用一个小的Perl脚本 cws2fws 来处理它:
perl cws2fws test.swf
这样会在同一个目录下生成一个名为 test.fws.swf
的新文件。
在FWS文件中查找配置URL
我使用了一个简单的命令:
strings test.fws.swf | grep http
结果是:
...
cookieOhttp://www.videodetective.net/flash/players/flashconfiguration.aspx?customerid=
...
有趣。让我们试着把已知的 customerid
、playerid
和 publishedid
参数放到这个URL中:
http://www.videodetective.net/flash/players/flashconfiguration.aspx?customerid=300120&playerid=351&publishedid=319113
如果我们在浏览器中打开这个链接,就能看到播放器的配置XML,这又指向了:
http://www.videodetective.net/flash/players/playlist.aspx?videokbrate=450&version=4.6&customerid=300120&fmt=3&publishedid=&sub=
现在如果我们打开这个链接,就能最终看到源URL:
http://cdn.videodetective.net/svideo/mp4/450/6993/293732.mp4?c=300120&r=450&s=293732&d=153&sub=&ref=&fmt=4&e=20111228220329&h=03e5d78201ff0d2f7df9a
现在我们可以下载这个h264视频文件,任务就完成了。
在Python脚本中自动化整个过程
这是一项完全不同的任务(留给读者自己去尝试)。