python爬取抖音視頻的實例分析

現在抖音的火爆程度,大傢都是有目共睹的吧,之前小編在網絡上發現好玩的事情,就是去爬取一些網站,因此,也考慮能否進行抖音上的破案去,在實際操作以後,真的實現出來瞭,利用自動化工具,就可以輕松實現瞭,後有小夥伴提出把appium去掉瘦身之後也是可以實現的,那麼看下詳細操作內容吧。

1、mitmproxy/mitmdump抓包

import requests
path = 'D:/video/'
num = 1788
def response(flow):
 global num
 target_urls = ['url']
 for url in target_urls:
   if flow.request.url.startswith(url):
      filename = path + str(num) + '.mp4
   res = requests.get(flow.request.url, stream=True)
    with open(filename, 'ab') as f:
    f.write(res.content)
    f.flush()
    print(filename + '下載完成')
   num += 1

2、Appium對手機進行模擬操作

利用Start Server按鈕即可啟動appium服務

再點擊Start Session即可啟動Android手機上的抖音app並進入到啟動頁面

3、python腳本來驅動app,直接在pycharm運行即可

實例擴展:

import requests
import json
import re
import os
from pprint import pprint as pp
import queue


class DouYin:
 header = {
  'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'zh-CN,zh;q=0.9',
  'cache-control': 'max-age=0',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
 }

 def __init__(self, url=None):
  self.url = self.get_RealAddress(url)
  # 獲取用戶視頻的url
  self.user_video_url = 'https://www.douyin.com/aweme/v1/aweme/post/?{0}'
  self.user_id = re.search(r'user/(.*)\?', self.url).group(1)		# 用戶id
  requests.packages.urllib3.disable_warnings()
  self.session = requests.Session()
  self.target_folder = ''		# 創建文件的路徑
  self.queue = queue.Queue()		# 生成一個隊列對象

 def user_info(self):
  self.mkdir_dir()
  p = os.popen('node fuck.js %s' % self.user_id) # 獲取加密的signature
  signature = p.readlines()[0]

  user_video_params = {
   'user_id': str(self.user_id),
   'count': '21',
   'max_cursor': '0',
   'aid': '1128',
   '_signature': signature
  }

  # 獲取下載視頻的列表
  def get_aweme_list(max_cursor=None):
   if max_cursor:
    user_video_params['max_cursor'] = str(max_cursor)
   user_video_url = self.user_video_url.format(
    '&'.join([key + '=' + user_video_params[key] for key in user_video_params])) # 拼接參數
   response = requests.get(
    url=user_video_url, headers=self.header, verify=False)
   contentJson = json.loads(response.content.decode('utf-8')) # 將返回的進行utf8編碼
   aweme_list = contentJson.get('aweme_list', [])
   for aweme in aweme_list:
    video_name = aweme.get(
     'share_info', None).get('share_desc', None)  # 視頻的名字
    video_url = aweme.get('video', None).get('play_addr', None).get(
     'url_list', None)[0].replace('playwm', 'play')  # 視頻鏈接
    self.queue.put((video_name, video_url)) # 將數據進隊列
   if contentJson.get('has_more') == 1: # 判斷後面是不是還有是1就是還有
    return get_aweme_list(contentJson.get('max_cursor')) # 有的話獲取參數max_cursor
  get_aweme_list()

 # 下載視頻
 def get_download(self):
  while True:
   video_name, video_url = self.queue.get()
   file_name = video_name + '.mp4'
   file_path = os.path.join(self.target_folder, file_name)
   if not os.path.isfile(file_path):
    print('download %s form %s.\n' % (file_name, video_url))
    times = 0
    while times < 10:
     try:
      response = requests.get(
       url=video_url, stream=True, timeout=10, verify=False) # 開啟流下載
      with open(file_path, 'wb') as f:
       for chunk in response.iter_content(1024): # 返回迭代對象
        f.write(chunk)
       print('下載成功')
      break
     except:
      print('下載失敗')
     times += 1

 # 創建對應的文件夾

 def mkdir_dir(self):
  current_folder = os.getcwd()
  self.target_folder = os.path.join(
   current_folder, 'download/%s' % self.user_id)
  if not os.path.isdir(self.target_folder):
   os.mkdir(self.target_folder)

 # 短鏈接轉長地址
 def get_RealAddress(self, url):
  if url.find('v.douyin.com') < 0:
   return url
  response = requests.get(
   url=url, headers=self.header, allow_redirects=False) # allow_redirects 允許跳轉
  return response.headers['Location']

if __name__ == '__main__':
 douyin = DouYin(url='http://v.douyin.com/J2B9Sk/')
 douyin.user_info()
 douyin.get_download()

到此這篇關於python爬取抖音視頻的實例分析的文章就介紹到這瞭,更多相關如何使用python爬取抖音視頻內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: