如何使用Python boto3通过Amazon S3 URI下载公共存储桶图片
报错原因
你遇到的botocore.exceptions.NoCredentialsError是boto3默认行为导致的:初始化S3客户端时,boto3会默认尝试从本地环境、AWS配置文件等位置加载身份凭证,而公开可读的S3存储桶不需要任何身份验证,将客户端配置为匿名访问模式即可解决该问题。
可直接运行的修改后脚本
import boto3 from botocore import UNSIGNED from botocore.config import Config def find_bucket_key(s3_path): """ 辅助函数:从去掉s3://前缀的路径中拆分桶名和对象key """ s3_components = s3_path.split('/') bucket = s3_components[0] s3_key = "" if len(s3_components) > 1: s3_key = '/'.join(s3_components[1:]) return bucket, s3_key def split_s3_bucket_key(s3_path): """ 拆分S3 URI为桶名和对象key,支持s3://前缀格式 :return: (桶名字符串, 对象key字符串) """ if s3_path.startswith('s3://'): s3_path = s3_path[5:] return find_bucket_key(s3_path) # 核心修改:配置客户端为匿名访问模式,不校验凭证 client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) s3_uri = 's3://some-name-with-hyphens/other/and_one_more/some.jpg' bucket_name, key_name = split_s3_bucket_key(s3_uri) # 下载文件到本地,自定义本地保存路径即可 local_save_path = 'downloaded_image.jpg' with open(local_save_path, 'wb') as f: client.download_fileobj(bucket_name, key_name, f) print(f"文件已下载至:{local_save_path}")
额外说明
- 如果访问时出现区域不匹配报错,可以在创建S3客户端时补充
region_name参数,示例:client = boto3.client('s3', region_name='us-east-1', config=Config(signature_version=UNSIGNED)),将参数值替换为你的存储桶实际所属区域即可 - 批量下载时只需将所有S3 URI放入列表,循环执行拆分、下载逻辑即可
- 下载大体积文件时该脚本默认使用流式写入,不会占用过多内存
内容的提问来源于stack exchange,提问作者PO_
相关产品推荐
相关产品推荐

