import requests import mimetypes import os def download_file(url, local_filename): try: with requests.get(url, stream=True) as response: response.raise_for_status() # 确保请求成功,否则抛出异常 # 获取文件类型并设置适当的文件扩展名 content_type = response.headers.get('Content-Type') extension = mimetypes.guess_extension(content_type, strict=False) if not extension: # 如果无法猜测扩展名,默认使用 .bin extension = '.bin' full_filename = local_filename + extension # 追加扩展名 with open(full_filename, 'wb') as file: for chunk in response.iter_content(chunk_size=8192): file.write(chunk) print(f"File downloaded successfully and saved as {full_filename}") return full_filename # 返回文件的完整路径 except requests.HTTPError as e: print(f"HTTP Error: {e}") return None except requests.RequestException as e: print(f"Error downloading the file: {e}") return None except Exception as e: print(f"An error occurred: {e}") return None if __name__ == '__main__': # 测试下载的URL test_url = "https://bid-assistance.oss-cn-wuhan-lr.aliyuncs.com/tender/28f7c0af7c7041bbbdf88ce6848e8a38.pdf?Expires=1722165340&OSSAccessKeyId=TMP.3KfNYFQchGtZWbjd2M1jR6y7PPqYTq1QLZ4pzbfEwkz3LwGLepVvr9371bndcRoMhHFhohaUJxrhiL63jKoAZk6VWQfwh4&Signature=RmktXAOwEbP1BBrkSfARfHtuXh8%3D" # 基本的本地文件名,不包括扩展名 local_file_name = 'C:\\Users\\zhangsan\\Desktop\\temp\\downloaded_file' file_path = download_file(test_url, local_file_name) if file_path: print(f"Downloaded file path: {file_path}")