摘錄自:LOMOOO “爬取網頁的ts視頻流”,lomooots

來源:互聯網
上載者:User

摘錄自:LOMOOO “爬取網頁的ts視頻流”,lomooots

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)+'.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表示的是線程池。這樣就可以實現線程裡面的並發了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.