You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用R获取公开Amazon S3存储桶文件名实现tif文件批量下载

问题原因
  • 你用于爬取的index.html?prefix=开头的地址是AWS S3的Web浏览前端,内容由JavaScript动态渲染,rvest、XML等静态爬取工具无法获取渲染后的下载链接,因此返回空结果。
  • aws.s3包的get_bucket_df不需要传入完整的访问地址,仅需传入纯桶名,目标目录前缀作为prefix参数单独传入,同时公开访问的桶需要额外添加anon = TRUE参数,跳过身份验证流程。
解决代码

步骤1:获取目标目录下所有tif文件列表

# 未安装包先执行 install.packages("aws.s3")
library(aws.s3)

# 配置桶名和目标目录前缀
bucket_name <- "prd-tnm"
target_prefix <- "StagedProducts/Elevation/OPR/Projects/WI_AshlandIronFlorence_2019_D19/WI_Ashland_4_2019/TIFF/"

# 拉取目标目录下所有文件的元数据
bucket_df <- get_bucket_df(
  bucket = bucket_name,
  prefix = target_prefix,
  anon = TRUE
)

# 筛选出所有tif格式文件
tif_files <- bucket_df[grepl("\\.tif$", bucket_df$Key), ]

步骤2:批量下载文件

方案1:使用aws.s3内置下载方法(更稳定)

# 配置本地保存目录,可自行修改
save_dir <- "./usgs_3dep_tif/"
dir.create(save_dir, recursive = TRUE, showWarnings = FALSE)

# 遍历下载,自动跳过已下载文件
for (key in tif_files$Key) {
  local_path <- file.path(save_dir, basename(key))
  if (!file.exists(local_path)) {
    save_object(
      object = key,
      bucket = bucket_name,
      file = local_path,
      anon = TRUE
    )
    cat("已完成下载:", basename(key), "\n")
  } else {
    cat("文件已存在,跳过:", basename(key), "\n")
  }
}

方案2:使用传统download.file方法

# 配置本地保存目录,可自行修改
save_dir <- "./usgs_3dep_tif/"
dir.create(save_dir, recursive = TRUE, showWarnings = FALSE)
base_download_url <- sprintf("https://%s.s3.amazonaws.com/", bucket_name)

# 遍历下载
for (key in tif_files$Key) {
  file_url <- paste0(base_download_url, key)
  local_path <- file.path(save_dir, basename(key))
  if (!file.exists(local_path)) {
    download.file(file_url, destfile = local_path, mode = "wb")
    cat("已完成下载:", basename(key), "\n")
  } else {
    cat("文件已存在,跳过:", basename(key), "\n")
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:09:04