Python获取短视频

import re
import requests
import json
import time

headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4557.4 Safari/537.36'}
#获取重新定向后的链接
url = 'https://v.douyin.com/Jp4ogoW'
url2 = requests.get(url,headers=headers).url

#正则提取链接中的item_ids
item_ids=re.search(r'\d+',url2).group(0)

#请求/api/v2/aweme/iteminfo接口,拿到视频信息
url='https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids='
video_info = requests.get(url+item_ids,headers=headers).text

#得到的信息需要转为json对象
video_url=json.loads(video_info)
video_url=video_url['item_list'][0]['video']['play_addr']['url_list'][0]

#用字符串替换去掉wm
video_url=video_url.replace('playwm','play')



#请求链接,并保存到本地。
res = requests.get(video_url,headers=headers)
open(time.strftime('%Y%m%d%H%M%S')+".mp4", "wb").write(res.content)
补充PHP版本
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://v.douyin.com/Jp4ogoW');
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
$info = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL);
curl_close($ch);
preg_match('/\d+/',$info,$match);
$content=file_get_contents('https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids='.$match[0]);
$video_url=str_replace('playwm','play',json_decode($content,true)['item_list'][0]['video']['play_addr']['url_list'][0]);
ini_set('user_agent', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1');
file_put_contents(time().'.mp4',file_get_contents($video_url));

Python获取短视频

上一篇:简单小爬虫


下一篇:HttpRunner3.X - 全面讲解如何落地项目实战