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

Ubuntu系统下Java Selenium Chrome点击下载文件失败求助

解决Ubuntu下ChromeDriver无头模式下载文件不生效的问题

针对你遇到的文件未下载到指定目录的问题,下面是几个关键的排查和修复点:

1. 补充无头模式的必要配置

Chrome无头模式下需要额外添加参数才能让下载配置生效,比如禁用共享内存限制、明确关闭下载提示:

chromeOptions.addArguments("--disable-dev-shm-usage");
chromePrefs.put("download.prompt_for_download", false);
chromePrefs.put("download.directory_upgrade", true);
chromePrefs.put("profile.content_settings.exceptions.automatic_downloads.*.setting", 1);

2. 替换隐式等待为文件下载完成的显式等待

你当前用的implicitlyWait是等待元素加载的,无法确保文件下载完成。需要添加代码等待目标文件出现在指定目录:

// 点击下载后,循环等待json文件出现
File downloadDir = new File(downloadFilepath);
File[] downloadedFiles = downloadDir.listFiles((dir, name) -> name.endsWith(".json"));
int waitTime = 0;
while (downloadedFiles == null || downloadedFiles.length == 0) {
    Thread.sleep(1000);
    downloadedFiles = downloadDir.listFiles((dir, name) -> name.endsWith(".json"));
    waitTime++;
    if (waitTime > 30) { // 最多等待30秒
        System.out.println("文件下载超时");
        break;
    }
}

3. 检查ChromeDriver与Chrome版本兼容性

确保ChromeDriver版本和本地Chrome浏览器大版本完全匹配(比如Chrome 114对应ChromeDriver 114.x)。可以通过以下命令查看Chrome版本:

google-chrome --version

替换对应版本的ChromeDriver后,记得赋予执行权限:

sudo chmod +x /usr/bin/chromedriver

4. 修正URL和路径细节

访问本地应用时补充http://协议,避免浏览器解析错误;同时用标准化方式获取绝对路径:

String downloadFilepath = new File("/tmp/").getAbsolutePath();
driver.get("http://localhost:8080");

修改后的完整代码

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class Downloadfile {

    public static void main(String[] args) throws InterruptedException {
        try {
            String downloadFilepath = new File("/tmp/").getAbsolutePath();
            HashMap<String, Object> chromePrefs = new HashMap<>();
            chromePrefs.put("profile.default_content_settings.popups", 0);
            chromePrefs.put("download.default_directory", downloadFilepath);
            chromePrefs.put("download.prompt_for_download", false);
            chromePrefs.put("download.directory_upgrade", true);
            chromePrefs.put("profile.content_settings.exceptions.automatic_downloads.*.setting", 1);

            System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.addArguments("--headless");
            chromeOptions.addArguments("--no-sandbox");
            chromeOptions.addArguments("--disable-dev-shm-usage");
            chromeOptions.setExperimentalOption("prefs", chromePrefs);

            WebDriver driver = new ChromeDriver(chromeOptions);
            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

            driver.get("http://localhost:8080");

            WebElement element = driver.findElement(By.xpath("/html/body/div/div/div/div[2]/div/main/section/div[1]/div[1]"));
            ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);

            // 等待文件下载完成
            File downloadDir = new File(downloadFilepath);
            File[] downloadedFiles = downloadDir.listFiles((dir, name) -> name.endsWith(".json"));
            int waitTime = 0;
            while (downloadedFiles == null || downloadedFiles.length == 0) {
                Thread.sleep(1000);
                downloadedFiles = downloadDir.listFiles((dir, name) -> name.endsWith(".json"));
                waitTime++;
                if (waitTime > 30) {
                    System.out.println("文件下载超时");
                    break;
                }
            }

            if (downloadedFiles != null && downloadedFiles.length > 0) {
                System.out.println("文件已下载到: " + downloadedFiles[0].getAbsolutePath());
            }

            driver.quit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:03:27