用python从微信视频号下载视频
时间: 2023-08-03 11:02:35 浏览: 981
微信视频号视频下载工具
5星 · 资源好评率100%
微信视频号下载需要模拟用户登录并获取视频的链接,然后通过 HTTP 请求下载视频。以下是一个简单的 Python 实现:
```python
import requests
import json
import re
# 模拟登录,获取 cookie
def login(username, password):
url = 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Referer': 'https://mp.weixin.qq.com/'
}
data = {
'username': username,
'pwd': password,
'imgcode': '',
'f': 'json'
}
session = requests.Session()
r = session.post(url, headers=headers, data=data)
if r.status_code == 200:
res = json.loads(r.text)
if res['base_resp']['err_msg'] == 'ok':
return session.cookies.get_dict()
# 获取视频链接
def get_video_link(url, cookie):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Referer': url,
'Cookie': '; '.join([f'{k}={v}' for k, v in cookie.items()])
}
r = requests.get(url, headers=headers)
if r.status_code == 200:
m = re.search(r'vid:\s*\'(.+?)\'', r.text)
if m:
vid = m.group(1)
api_url = f'https://mp.weixin.qq.com/mp/videoplayer?action=get_mp_video_play_url&preview=0&__biz=MzAxNTI4MTM3Mw==&mid=2650820022&idx=1&vid={vid}&uin=&key=&pass_ticket=&wxtoken=&appmsg_token=&x5=0&f=json'
r = requests.get(api_url, headers=headers)
if r.status_code == 200:
res = json.loads(r.text)
if res['base_resp']['err_msg'] == 'ok':
return res['url_info'][0]['url']
# 下载视频
def download_video(url, cookie, filename):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Referer': url,
'Cookie': '; '.join([f'{k}={v}' for k, v in cookie.items()])
}
r = requests.get(url, headers=headers, stream=True)
if r.status_code == 200:
with open(filename, 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
# 使用示例
cookie = login('your_username', 'your_password')
url = 'https://mp.weixin.qq.com/s/1QZjVp6YwYVlKQs1jzVX1g'
video_link = get_video_link(url, cookie)
download_video(video_link, cookie, 'video.mp4')
```
请注意,上述代码仅供参考,具体实现可能需要根据实际情况进行修改。同时,下载他人视频涉及到版权问题,请谨慎使用。
阅读全文