如何读取Manifest文件从带通配符URL获取最新Gentoo镜像文件名?
从Manifest文件获取最新Gentoo stage3文件的正确姿势
你原来的代码靠爬取页面HTML匹配文件名,其实同一目录下的Manifest文件已经整理好了最新文件列表,直接读它更靠谱,具体实现如下:
修改思路
- 定位Manifest文件:它就在你指定的
ARCH_URL目录下,直接拼接Manifest即可访问 - 解析Manifest内容:Manifest每行对应一个文件,格式为
哈希类型 哈希值 文件名,我们只需要筛选出以ARCH_TYPE开头、.tar.xz结尾的条目,提取文件名 - 生成最新下载链接:用提取到的最新文件名替换硬编码的旧文件名,就能拿到对应文件的下载地址
完整代码
import requests from pathlib import Path ARCH_TYPE = "stage3-amd64-desktop-systemd" ARCH_URL = f"https://distfiles.gentoo.org/releases/amd64/autobuilds/current-{ARCH_TYPE}/" MANIFEST_URL = f"{ARCH_URL}Manifest" # 获取并解析Manifest文件 response = requests.get(MANIFEST_URL) response.raise_for_status() # 请求失败时直接抛出异常 manifest_content = response.text # 筛选目标文件的最新文件名 latest_arch_file = None for line in manifest_content.splitlines(): line_parts = line.strip().split() # 匹配符合特征的文件名 if len(line_parts) >= 3 and line_parts[-1].startswith(ARCH_TYPE) and line_parts[-1].endswith(".tar.xz"): latest_arch_file = line_parts[-1] break if latest_arch_file: print(f"找到最新文件: {latest_arch_file}") FILEPATH = Path(latest_arch_file) SRC_URL = f"{ARCH_URL}{latest_arch_file}" # 这里可以添加下载逻辑,例如: # with open(FILEPATH, 'wb') as f: # f.write(requests.get(SRC_URL).content) else: print(f"未找到匹配{ARCH_TYPE}的.tar.xz文件")
代码说明
- 用
requests库处理HTTP请求,比urlopen更简洁,还能自动处理编码和异常 - 直接遍历Manifest条目筛选文件名,不需要解析HTML,避免页面结构变化导致的匹配失败问题
- 逻辑简单直接,稳定性和可靠性比原方法更高
内容的提问来源于stack exchange,提问作者megalamehaxxor
相关产品推荐
相关产品推荐

