import requests,re,os,asyncio,aiofiles,aiohttp
m3u8_url='https://baidu.sd-play.com/20230411/jiJlSz5Z/1200kb/hls/index.m3u8?skipl=1'
def download_m3u8():
res=requests.get(m3u8_url)
if res.status_code==200:
folder_path = "./m3u8"
if not os.path.exists(folder_path):
os.makedirs(folder_path)
with open(folder_path+'/second_m3u8.txt','w',encoding='utf-8') as f:
f.write(res.text)
print('下载m3u8完成')
async def download_one(url):
for i in range(10):
try:
file_name=url.split('/')[-1]
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
content=await resp.content.read()
async with aiofiles.open(f'./电影_源_加密后/{file_name}',mode='wb') as fa:
await fa.write(content)
await fa.close() # 添加这一行来关闭文件
print(url,'下载成功')
except:
print('下载失败',url)
await asyncio.sleep((i+1)*5) #可以适当的进行睡眠
# async def download_all_ts():
# tasks=[]
# async with aiofiles.open('./m3u8/second_m3u8.txt',mode='r',encoding='utf-8') as f:
# async for line in f:
# if line.startswith('#'):
# continue
#
# task=asyncio.create_task(download_one(line.strip()))
# tasks.append(task)
# await asyncio.gather(*tasks)
async def download_all_ts():
tasks=[]
async with aiofiles.open('./m3u8/second_m3u8.txt',mode='r',encoding='utf-8') as f:
async for line in f:
if line.startswith('#'):
continue
# 控制同时打开的文件数量
print(line.strip())
async with asyncio.Semaphore(300):
task=asyncio.create_task(download_one(line.strip()))
tasks.append(task)
await asyncio.gather(*tasks)
if __name__ == '__main__':
# download_m3u8()
even_loop=asyncio.get_event_loop()
even_loop.run_until_complete(download_all_ts())
even_loop.close()
运行 报错:Traceback (most recent call last):
File "D:/pythonProject/多线程/10协程下载m3u8电影.py", line 56, in <module>
even_loop.run_until_complete(download_all_ts())
File "D:\Python37\lib\asyncio\base_events.py", line 570, in run_until_complete
self.run_forever()
File "D:\Python37\lib\asyncio\base_events.py", line 538, in run_forever
self._run_once()
File "D:\Python37\lib\asyncio\base_events.py", line 1746, in _run_once
event_list = self._selector.select(timeout)
File "D:\Python37\lib\selectors.py", line 323, in select
r, w, _ = self._select(self._readers, self._writers, [], timeout)
File "D:\Python37\lib\selectors.py", line 314, in _select
r, w, x = select.select(r, w, w, timeout)
ValueError: too many file descriptors in select()
该怎么解决呢 ? 最大并发数 我都改写成2 了 还是 报错
我想知道有没有获取到数据呢