一、步骤代码
1、访问网站
提示:一定要带上user-agen。
2、文件是否存在
提示:判断相同名字的文件删除,不然后期会出现报错。
if os.path.exists(outfile_name):
os.remove(outfile_name)
3、文件存储
提示:进行时,记得入口链接补全。
link_content = requests.get(url_ts, headers=headers, timeout=25).content
with open(outfile_name, 'ab+') as f:
f.write(link_content)
二、代码整合
import os
import requests,re
from lxml import etree
from tqdm import tqdm
def resp(url):
global lin_res
global m3u8_url_l
global outfile_name
global name
resp = requests.get(url, headers=headers)
r = etree.HTML(resp.text)
name = "".join(r.xpath('//head/title/text()')[0].split()[:2])
outfile_name = 'D:/' + name + '.mp4'
if os.path.exists(outfile_name):
os.remove(outfile_name)
lin_res = '/'.join(re.findall(r'\"backupUrl\\":...(.*?)\"].'
, resp.text)[0].split('/')[:-1])+'/'
m3u8_url_l = re.findall(r'\"backupUrl\\":...(.*?)\"].', resp.text)
def m3u8():
while True:
print('清晰度 1:1080P,2:720P,3:540P,4:320P')
a = int(input("请选择清晰度: "))
if a == 1:
m3u8_url = m3u8_url_l[1]
elif a == 2:
m3u8_url = m3u8_url_l[2]
elif a == 3:
m3u8_url = m3u8_url_l[3]
elif a == 4:
m3u8_url = m3u8_url_l[4]
else:
continue
m3u8_data = requests.get(m3u8_url,headers=headers,timeout=5)
url_list = re.findall(r'EXTINF:.*,\n(.*?)\n',m3u8_data.text)
for url in tqdm(url_list,desc=f"正在下载 {name} "):
url_ts = lin_res + url
link_content = requests.get(url_ts, headers=headers, timeout=25).content
with open(outfile_name, 'ab+') as f:
f.write(link_content)
break
if __name__ == '__main__':
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
acf = input('ac需要下载ID:')
url = f'https://www.acfun.cn/v/{acf}'
print(url)
resp(url)
m3u8()
|