import requests
import os
from multiprocessing.dummy import Pool
# 在罕見的情況下,你可能想獲取來自服務器的原始套接字響應,那么你可以訪問 r.raw。 如果你確實想這么干,那請你確保在初始請求中設置了 stream=True。具體你可以這么做:
#
# >>> r = requests.get('https://github.com/timeline.json', stream=True)
# >>> r.raw
# <requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
# >>> r.raw.read(10)
# '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
# 但一般情況下,你應該以下面的模式將文本流保存到文件:
#
# with open(filename, 'wb') as fd:
# for chunk in r.iter_content(chunk_size):
# fd.write(chunk)
# 使用 Response.iter_content 將會處理大量你直接使用 Response.raw 不得不處理的。 當流下載時,上面是優先推薦的獲取內容方式。 Note that chunk_size can be freely adjusted to a number that may better fit your use cases.
#chunk_size可以設置你指定的大小,指定每次獲取數據的最大值,注意:並不是每次請求回來的content塊都是chunk_size指定的大小。
def download(j):
global picpath
url='http://xxx5%s'% str(j).zfill(3)+'.ts'
for l in range(20): #下載失敗情況最多20次
try:
retu = requests.get(url, stream=True)
print(str(j).zfill(3)+' 下載完成')
break
except:
print(u'%s文件,正在重試第%d次' % (str(j).zfill(3),l + 1))
picpath = r'C:\Users\bin\PycharmProjects\untitled\%s' % str(j).zfill(3) + '.ts'
file = open(picpath, 'wb')
for chunk in retu.iter_content(chunk_size=1024 * 8):
if chunk:
file.write(chunk)
file.flush()
file.close()
if __name__ == "__main__":
list = [i for i in range(0,2250)] #2250是我爬的視頻的長度
pool = Pool(4)
pool.map(download, list)
pool.close()
pool.join()
lst = []
for i in range(0,2250):
test = r'C:\Users\bin\PycharmProjects\untitled\abc\%s.ts' % str(i).zfill(3)
if not os.path.exists(test):
print(str(i).zfill(3)+'.ts')
lst.append(i)
print(lst)
if len(lst):
pool = Pool(4)
pool.map(download, lst)
pool.close()
pool.join()
else:
print
u'全部下載完成,正在合並'
os.system(r'copy/b C:\Users\bin\PycharmProjects\untitled\*.ts C:\Users\bin\PycharmProjects\untitled\new.ts')
print
u'合並完成'
# Python中線程multiprocessing模塊與進程使用的同一模塊。使用方法也基本相同,唯一不同的是,from multiprocessing import Pool這樣導入的Pool表示的是進程池;
# from multiprocessing.dummy import Pool這樣導入的Pool表示的是線程池。這樣就可以實現線程里面的並發了。