溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python怎么實(shí)現(xiàn)抖音視頻批量下載

發(fā)布時(shí)間:2021-04-12 13:43:33 來(lái)源:億速云 閱讀:362 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)python怎么實(shí)現(xiàn)抖音視頻批量下載,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

具體內(nèi)容如下

這里就拿最近很火的抖音視頻為例,利用API來(lái)實(shí)現(xiàn)用戶抖音視頻的批量下載

主要用到的模塊有

1、requests模塊;

2、bs4模塊;

import requests
import bs4
import os
import json
import re
import sys
import time
from contextlib import closing
requests.packages.urllib3.disable_warnings()
class Spider():
  def __init__(self):
    self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
            }
    print('[INFO]:Douyin App Video downloader...')
    print('[Version]: V1.0')
    print('[Author]: Charles')
  # 外部調(diào)用運(yùn)行
  def run(self):
    user_id = input('Enter the ID:')
    try:
      int(user_id)
    except:
      print('[Error]:ID error...')
      return
    video_names, video_urls, nickname = self._parse_userID(user_id)
    if nickname not in os.listdir():
      os.mkdir(nickname)
    print('[INFO]:Number of Videos <%s>' % len(video_urls))
    for num in range(len(video_names)):
      print('[INFO]:Parsing <No.%d> <Url:%s>' % (num+1, video_urls[num]))
      temp = video_names[num].replace('\\', '')
      video_name = temp.replace('/', '')
      self._downloader(video_urls[num], os.path.join(nickname, video_name))
      print('\n')
    print('[INFO]:All Done...')
  # 視頻下載
  def _downloader(self, video_url, path):
    size = 0
    download_url = self._get_download_url(video_url)
    with closing(requests.get(download_url, headers=self.headers, stream=True, verify=False)) as response:
      chunk_size = 1024
      content_size = int(response.headers['content-length'])
      if response.status_code == 200:
        sys.stdout.write('[File Size]: %0.2f MB\n' % (content_size/chunk_size/1024))
        with open(path, 'wb') as f:
          for data in response.iter_content(chunk_size=chunk_size):
            f.write(data)
            size += len(data)
            f.flush()
            sys.stdout.write('[Progress]: %0.2f%%' % float(size/content_size*100) + '\r')
            sys.stdout.flush()
  # 獲得視頻下載地址
  def _get_download_url(self, video_url):
    res = requests.get(url=video_url, verify=False)
    soup = bs4.BeautifulSoup(res.text, 'lxml')
    script = soup.find_all('script')[-1]
    video_url_js = re.findall('var data = \[(.+)\];', str(script))[0]
    html = json.loads(video_url_js)
    return html['video']['play_addr']['url_list'][0]
  # 通過(guò)user_id獲取該用戶發(fā)布的所有視頻
  def _parse_userID(self, user_id):
    video_names = []
    video_urls = []
    unique_id = ''
    while unique_id != user_id:
      search_url = 'https://api.amemv.com/aweme/v1/discover/search/?keyword={}&count=10&type=1&aid=1128'.format(user_id)
      res = requests.get(url=search_url, verify=False)
      res_dic = json.loads(res.text)
      uid = res_dic['user_list'][0]['user_info']['uid']
      aweme_count = res_dic['user_list'][0]['user_info']['aweme_count']
      nickname = res_dic['user_list'][0]['user_info']['nickname']
      unique_id = res_dic['user_list'][0]['user_info']['unique_id']
    user_url = 'https://www.douyin.com/aweme/v1/aweme/post/?user_id={}&max_cursor=0&count={}'.format(uid, aweme_count)
    res = requests.get(url=user_url, verify=False)
    res_dic = json.loads(res.text)
    i = 1
    for each in res_dic['aweme_list']:
      share_desc = each['share_info']['share_desc']
      if '抖音-原創(chuàng)音樂(lè)短視頻社區(qū)' == share_desc:
        video_names.append(str(i) + '.mp4')
        i += 1
      else:
        video_names.append(share_desc + '.mp4')
      video_urls.append(each['share_info']['share_url'])
    return video_names, video_urls, nickname
if __name__ == '__main__':
  sp = Spider()
  sp.run()

python怎么實(shí)現(xiàn)抖音視頻批量下載

關(guān)于“python怎么實(shí)現(xiàn)抖音視頻批量下載”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI