Home  >  Article  >  Backend Development  >  How to download videos in python

How to download videos in python

(*-*)浩
(*-*)浩Original
2019-07-02 11:00:489065browse

When crawling, it is often necessary to save videos locally. Usually you have to first obtain the download link of the video (.mp4), and then set the path to save it locally (the path includes the last name,

, for example: D:/1.mp4), so The parameters passed in by the function are url and path.

How to download videos in python

##Example: (Recommended learning: Python video tutorial)

import os,import requests。
def download_video(url, file_path):
	try:
		headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.3.2.1000 Chrome/30.0.1599.101 Safari/537.36"}
		pre_content_length = 0
		# 循环接收视频数据
		while True:# 若文件已经存在,则断点续传,设置接收来需接收数据的位置    
			if os.path.exists(file_path):
				headers['Range'] = 'bytes=%d-' % os.path.getsize(file_path)
			res = requests.get(url, stream=True, headers=headers)
			content_length = int(res.headers['content-length'])
			# 若当前报文长度小于前次报文长度,或者已接收文件等于当前报文长度,则可以认为视频接收完成
			if content_length < pre_content_length or (os.path.exists(file_path) and os.path.getsize(file_path) >= content_length):
				break
			pre_content_length = content_length
			# 写入收到的视频数据
			with open(file_path, 'ab') as file:
				file.write(res.content)
				file.flush()
				print('receive data,file size : %d   total size:%d' % (os.path.getsize(file_path), content_length))
	except Exception as e:
		dic = {'url':url, 'file_path':file_path}
		print("下载失败:", dic)

The requests and os libraries are used here, so import os and import requests are required.

For more Python-related technical articles, please visit the

Python Tutorial column to learn!

The above is the detailed content of How to download videos in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn