在 Python 中以 ASCII 文本形式下载文件

问题描述 投票:0回答:1

我编写了这段代码来下载包文件。但是,虽然我能够下载数据,但文件类型被识别为 ASCII 文本,并且存在二进制数据。当我通过 Chrome 下载数据时,该文件会作为包含多个 RPM 的 zip 文件下载。我已确保标头和有效负载中的所有参数与通过 Chrome 检查获取的参数一致。但是,我不确定代码中有什么错误或缺失。请帮忙。

注意:- 根据负载信息下载包。不同的操作系统有不同的有效负载。

[***** ~]# file linux-client-bundle.ext
linux-client-bundle.ext: ASCII text, with very long lines, with no line terminators

 url = "abc.com/plugin/products/client-management/v2/downloads/download"  
api_token = 'token-1234'  
headers = {
    'session': api_token,  
    'Accept-Encoding': 'gzip, deflate, br',  
}

# Define the payload (JSON data)
payload = {
    "category_file": {
        "category": "CATEGORY_LINUX",
        "file_type": "FILE_TYPE_BUNDLE"
    }
}
response = requests.post(url, headers=headers, verify=False, json=payload, stream=True)
if response.status_code == 200:
    print("First few bytes of binary data:", response.content[:10])
    with open("linux-client-bundle.ext", "wb") as fd:
       for chunk in response.iter_content(chunk_size=128):
         fd.write(chunk)
    print("File downloaded successfully as:")
else:
    print("Error:", response.status_code)
python download package
1个回答
0
投票
import requests
import base64


# Define the URL of the file to download
url = "abc"

api_token = ''


headers = {
    'session': api_token,
    'Accept-Encoding': 'gzip, deflate, br, zstd',
}

# Define the payload (JSON data)
payload = {
    "category_file": {
        "category": "CATEGORY_LINUX",
        "file_type": "FILE_TYPE_BUNDLE"
    }
}

# Send a GET request with the payload to download the file
response = requests.post(url, headers=headers, verify=False, json=payload, stream=True)
#content_type = response.headers.get('Content-Type')
# Check if the request was successful (status code 200)
data = response.json()
content = data.get('content', '')
decoded_content = base64.b64decode(content)
with open("downloaded_file.zip", "wb") as file:
      file.write(decoded_content)

print("File downloaded successfully.")
© www.soinside.com 2019 - 2024. All rights reserved.