从互联网上下载文件python代码

def download_file(url, filename):
	"""将链接中的数据存储入文件中。

	Args:
		url: 链接。
		filename: 文件路径名。
	Raises:
		KeyboardInterrupt: 用户按^C引发异常。
		Exception: 发生异常。
	"""
	if os.path.exists(filename):
		print('file '+filename+' exists!')
		return filename
	try:
		time.sleep(random.randint(1,7))
		r = requests.get(url, stream=True, timeout=60,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'})
		r.raise_for_status() # 建立连接
		with open(filename, 'wb') as f:
			for chunk in r.iter_content(chunk_size=1024): # 分块写入二进制内容
				if chunk:
					f.write(chunk)
					f.flush()
		print('downloading '+filename+' successfully!')
		return filename
	except KeyboardInterrupt:
		if os.path.exists(filename):
			os.remove(filename)
		raise KeyboardInterrupt
	except Exception:
		traceback.print_exc()
		if os.path.exists(filename):
			os.remove(filename)

如果曾经下载成功或刚才下载成功文件,返回文件名,若现在下载失败返回None,可根据download_file的返回值是否为None,判定失败次数

创建于2412251740,修改于2412251740

posted @ 2024-12-25 17:42  园糯  阅读(22)  评论(0)    收藏  举报