下载文件到本地
import os import requests
def DownloadFile(mp3_url, save_url,file_name): try: if mp3_url is None or save_url is None or file_name is None: print(‘参数错误’) return None # 文件夹不存在,则建立文件夹 folder = os.path.exists(save_url) if not folder: os.makedirs(save_url) # 读取MP3资源 res = requests.get(mp3_url,stream=True) # 获取文件地址 file_path = os.path.join(save_url, file_name) print(‘开始写入文件:’, file_path) # 打开本地文件夹路径file_path,以二进制流方式写入,保存到本地 with open(file_path, ‘wb’) as fd: for chunk in res.iter_content(): fd.write(chunk) print(file_name+’ 成功下载!’) except: print(“程序错误”)
if name == “main”: # MP3源地址url #url = ‘https://online2.tingclass.net/lesson/shi0529/0009/9349/2.mp3’ dd = “https://down11.tingclass.net/textrar/lesson/0000/968/” #https://down11.tingclass.net/textrar/lesson/0000/968/082.doc for i in range(99, 100): ii = ‘’+str(i+1) #这里可以加判断 elif else 筛选1-9 ,10, 100 print(ii) url = f"{dd}{ii}.doc" # MP3保存文件夹 save_url=‘D:/英语听力练习/李阳疯狂英语标准美语发音宝典 /’ # MP3文件名 file_name = f"{ii}.doc" # file_name = ‘mymusic.mp3’ DownloadFile(url,save_url, file_name)
|