You need to enable JavaScript to run this app. 使用Python boto3检索下载S3存储桶全部PDF及AttributeError报错解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Python boto3检索下载S3存储桶全部PDF及AttributeError报错解决

S3全桶PDF检索下载问题修复方案

错误原因

报错AttributeError: 'str' object has no attribute 'objects'核心问题在于代码错误将存储桶的名称字符串(bucket.name返回值为字符串类型)作为操作对象调用了仅Bucket实例具备的objects属性。
此外原代码使用Prefix='.pdf'的筛选逻辑也不成立:Prefix用于匹配对象键的前缀,PDF属于文件后缀,无法通过前缀规则筛选。

修复后完整实现代码

import boto3
import os

# 初始化S3资源,需提前配置好AWS凭证(环境变量、~/.aws/credentials等方式均可)
s3 = boto3.resource('s3')
# 自定义本地PDF文件存储目录
local_pdf_dir = "./s3_download_pdfs"
os.makedirs(local_pdf_dir, exist_ok=True)

for bucket in s3.buckets.all():
    current_bucket_name = bucket.name
    print(f"正在扫描存储桶:{current_bucket_name}")
    # 直接使用Bucket实例调用objects属性
    for obj in bucket.objects.all():
        # 匹配PDF后缀,加lower()兼容.PDF大写后缀场景,不需要可删除
        if obj.key.lower().endswith('.pdf'):
            pdf_path = f"{current_bucket_name}/{obj.key}"
            print(f"匹配到PDF文件:{pdf_path}")
            # 生成本地存储路径,按存储桶名称分目录存储避免重名
            local_file_path = os.path.join(local_pdf_dir, current_bucket_name, obj.key)
            os.makedirs(os.path.dirname(local_file_path), exist_ok=True)
            # 执行下载
            bucket.download_file(obj.key, local_file_path)
            print(f"下载完成:{local_file_path}")

注意事项

  • 运行代码前请确保AWS凭证具备对应存储桶的s3:ListBucket和s3:GetObject权限
  • 如果存储桶内文件数量极大,可使用分页接口优化性能,常规场景上述代码可直接运行
  • 如需缩小扫描范围,可将bucket.objects.all()替换为bucket.objects.filter(Prefix="指定前缀路径/"),仅扫描指定路径下的文件

内容的提问来源于stack exchange,提问作者GuiEpi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 22:06:03