Python代码优化:处理m3u8文件并替换URL
以下代码用于处理以 '#YUMING|https' 开头的 m3u8 文件,并替换其中部分 URL。
import os
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9,ja-JP;q=0.8,ja;q=0.7',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Upgrade-Insecure-Requests': '1'
}
dir_path = input('请输入.m3u8文件所在目录的路径:')
for file_name in os.listdir(dir_path):
if file_name.endswith('.m3u8'):
print(f'处理文件: {file_name}')
file_path = os.path.join(dir_path, file_name)
with open(file_path, 'r') as f:
lines = f.readlines()
# 打印文件内容,检查是否存在以 '#YUMING|https' 开头的行
print('文件内容:')
for line in lines:
print(line.strip())
if '#YUMING|https' in lines[0]:
url = lines[0][lines[0].index('https'):lines[0].index('/-/')+3]
response = requests.post(url + 'playlist.m3u8', headers=headers)
if response.status_code == 200:
print('成功:' + str(response.status_code))
new_url = response.url
new_url = new_url[:new_url.index('playlist.m3u8')]
# 替换所有 'media_' 的 URL
new_lines = []
for line in lines:
if 'media_' in line:
line = line.replace('media_', new_url + 'media_')
# 删除以 '#YUMING|https' 开头的行
if line.startswith('#YUMING|https'):
continue
new_lines.append(line)
# 打印新的 lines,检查是否已删除该行
print('新的 lines:')
for line in new_lines:
print(line.strip())
# 写入新的文件
with open(file_path, 'w') as f:
for line in new_lines:
f.write(line)
else:
print('失效:' + str(response.status_code))
else:
if 'http' in lines[1]:
url = lines[1][lines[1].index('http'):lines[1].index('/-/')+3]
else:
url = lines[8][lines[8].index('http'):lines[8].index('/-/')+3]
response = requests.post(url + 'playlist.m3u8', headers=headers)
if response.status_code == 200:
print('成功:' + str(response.status_code))
new_url = response.url
new_url = new_url[:new_url.index('playlist.m3u8')]
# 替换所有 'http' 和 '/-/' 之间的 URL
new_lines = []
for line in lines:
if 'http' in line and '/-/' in line:
line = line[:line.index('http')] + new_url + line[line.index('/-/')+3:]
new_lines.append(line)
# 写入新的文件
with open(file_path, 'w') as f:
for line in new_lines:
f.write(line)
else:
print('失效:' + str(response.status_code))
代码优化点:
- 在处理文件前,打印文件内容,检查是否存在以 '#YUMING|https' 开头的行,方便排查问题。
- 在删除以 '#YUMING|https' 开头的行前,打印新的 lines,检查是否已成功删除该行。
- 优化代码结构,使用
continue语句跳过不符合条件的行,避免多余的循环操作。 - 使用更简洁的代码风格,例如使用
line.startswith('#YUMING|https')判断是否以该字符串开头。
注意事项:
- 确保目标文件存在并可读写。
- 检查网络连接是否正常。
- 可以根据实际需求调整代码中的 URL 和请求方法。
希望以上代码和优化建议能帮助你解决问题。
原文地址: https://www.cveoy.top/t/topic/nEns 著作权归作者所有。请勿转载和采集!