跳至正文

Python3 下载并解析 xml.gz 文件

问题场景:需要从网上获取一个以 GZip 格式压缩的 xml 文件,并使用 Python3 解析。

前提需求:希望直接解析 raw 数据而不是先保存为文件。

一般处理方法:先保存为文件,再通过 Python3 的 gzip 库 打开文件解析。

参考资料:Parsing a xml.gz file in pythontmpfile and gzip combination problem

代码实现(以 Xposed 模块官方仓库为例)

import gzip
import requests
import tempfile
from xml.etree import ElementTree

raw = requests.get("https://dl-xda.xposed.info/repo/full.xml.gz",
                   stream=True).raw.data
# 获取原始数据(bytes)
with tempfile.TemporaryFile(mode='w+b') as f:
    # 创建虚拟文件(生成在内存中,关闭即清除)
    f.write(raw)
    f.flush()
    f.seek(0)
    # 写入数据
    with gzip.GzipFile(mode='r', fileobj=f) as gzip_file:
        # 解析虚拟文件
        tree = ElementTree.parse(gzip_file)
        print(tree.getroot())
标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

🌍 Language