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

如何用Python实现点击触发文件下载?含Box站点自动下载需求

自动化下载Box共享文件夹文件(Google Colab + Python)

前置准备

在Colab中运行以下命令安装所需依赖:

!pip install selenium webdriver-manager

编写自动化脚本

以下代码实现完整的下载流程,包含页面跳转、元素等待和下载操作:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time

# 配置Chrome无头模式(适配Colab环境)
options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_experimental_option('prefs', {
    'download.default_directory': '/content/',  # 设置Colab下载目录
    'download.prompt_for_download': False,
    'download.directory_upgrade': True
})

# 初始化浏览器
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
wait = WebDriverWait(driver, 10)

try:
    # 打开目标Box共享链接
    driver.get("https://massdot.app.box.com/s/21j0q5di9ewzl0abt6kdh5x8j8ok9964")
    
    # 获取所有子文件/文件夹链接(根据页面实际元素调整选择器)
    item_links = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "a[aria-label*='item']")))
    link_urls = [link.get_attribute('href') for link in item_links]
    
    # 遍历每个链接,进入页面并点击下载
    for url in link_urls:
        driver.get(url)
        # 等待下载按钮加载并点击(根据页面实际元素调整选择器)
        download_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='download-btn']")))
        download_btn.click()
        time.sleep(2)  # 等待下载请求发送,可根据文件大小调整
    
    print("所有文件下载完成,保存路径:/content/")

finally:
    # 关闭浏览器
    driver.quit()

注意事项

  • 页面元素选择器可能因Box页面更新而变化,若脚本失效,需通过Colab的开发者工具(或手动查看页面源码)更新By.CSS_SELECTOR的参数。
  • 若遇到下载超时,可适当延长time.sleep()的时长或调整WebDriverWait的超时时间。
  • 下载的文件会保存在Colab的/content/目录下,可通过左侧文件面板查看或下载到本地。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:21:49