2015-09-15 57 views
0

我正在尝试使用python下载视频。如何使用多线程进行视频下载?

我试图加快使用多线程下载,但我无法在requestsurllib2中提出解决方案。

此外,如果任何人都可以给出一个代码如何解决这将是非常有益的。

这里是我试图代码:

import requests 
http_proxy = "http://edcguest:[email protected]:3128" 
https_proxy = "https://edcguest:[email protected]:3128" 
ftp_proxy = "ftp://edcguest:[email protected]:3128" 

proxyDict = { 
      "http" : http_proxy, 
      "https" : https_proxy, 
      "ftp" : ftp_proxy 
     } 

def download_file(url): 
    resume_byte_pos = 0 
    end_byte_pos = 432526330 
    # NOTE the stream=True parameter 
    resume_header = {'Range': 'bytes=%d-%d(resume_byte_pos,end_byte_pos)} 
    #r = requests.get(url, stream=True, proxies=proxyDict) 
    r = requests.get(url, stream=True,proxies=proxyDict,headers=resume_header) 
    print r.headers 


    with open('ab2.mp4', 'wb') as f: 
     for chunk in r.iter_content(chunk_size=1024): 
       if chunk: # filter out keep-alive new chunks 
        f.write(chunk) 
        f.flush() 

download_file('https://r2---sn-o3o-qxal.googlevideo.com/videoplayback?key=yt5&sver=3&signature=3D4D50B11C6206B737185B7A9887A72FE356C6DF.87458BB3BF357CEF131BEDF0C0ED3DC08F087646&upn=8n6wa_1gM_o&source=youtube&requiressl=yes&mime=video%2Fmp4&ip=14.139.249.194&expire=1442331973&ratebypass=yes&lmt=1441845538878516&mm=31&ipbits=0&mn=sn-o3o-qxal&pl=24&sparams=dur%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&fexp=9408710%2C9409069%2C9409170%2C9412773%2C9415365%2C9415485%2C9415942%2C9416023%2C9416126%2C9416333%2C9416729%2C9417707%2C9417710%2C9417818%2C9418153%2C9418162%2C9418200%2C9418245%2C9418448%2C9418986%2C9419773%2C9419788%2C9419837%2C9420348%2C9420777%2C9420798&id=o-ALtyLWP7o7PqDhINh6FWp4v4FC8-3pQoZ0UH4COW6v5p&mt=1442310331&dur=8384.609&mv=m&initcwndbps=4191250&ms=au&itag=18&cpn=zzjuCmNROtaupQMW&ptk=Apple%252Bvid&oid=ffsQQyXI443h2PgMzMjp-g&ptchn=E_M8A5yxnLfW0KghEeajjw&pltype=content&c=WEB&cver=html5') 
+1

也许使用'multiprocessing'而不是'threading'来实现下载瘫痪。 – yask

+0

服务器不支持部件需求。您无法加速下载视频。时间=文件大小/接收速度。 如果支持粒度,则必须使用其他系统资源来合并它们。 你可以像上面提到的那样做。 – dsgdfg

+1

关于stackoverflow的问题应该显示你尝试过的代码以及为什么你认为它不工作。请用你试过的东西更新你的问题。此外,请认真思考@ dsgdfg的评论。一些服务器可能支持请求块,但许多服务器可能不支持。 –

回答

1

urllib2 is not thread-safe,所以如果有threading使用注意事项适用。

但是,urllib3确实thread safe,所以你可以考虑使用它。

或者,如果你有,你不希望重写,你将使用批量下载您可以探索像CeleryGearman一个任务队列中的urllib2基于库。