All about

When using requests.get in Python to download a file, you can check the filename in advance by examining the HTTP response headers. Typically, the server uses the Content-Disposition header to inform the client about the filename of the transmitted file.
Here is a simple example code using the requests library to download a file and retrieve the filename.

import requests
import re
from urllib.parse import unquote

def get_filename_from_cd(content_disposition):
    """
    Extracts filename from Content-Disposition header.
    """
    if not content_disposition:
        return None
    match = re.search(r'filename="(.*)"', content_disposition)
    if match:
        filename = match.group(1)
        return unquote(filename)
    return None

url = "https://example.com/path/to/file.zip"
response = requests.get(url)

# Get the confirmed filename
filename = get_filename_from_cd(response.headers.get("Content-Disposition"))

# Download the file
with open(filename, "wb") as file:
    file.write(response.content)

print(f"File {filename} downloaded successfully.")

 

In this code, the get_filename_from_cd function extracts the filename from the Content-Disposition header. The function uses a regular expression to extract the filename from the header and performs URL decoding using urllib.parse.unquote.
By using this code, you can download a file, retrieve the filename provided by the server, and save it locally. If the filename is not present, the function returns None, and you can add appropriate exception handling based on your requirements.

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading