下面是一个示例代码,用于等待文件下载完成并获取文件名:

import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.Selenide;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;

public class FileDownloadExample {
    public static void main(String[] args) {
        // 设置 ChromeOptions,启用自动下载
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-notifications");
        options.addArguments("--disable-popup-blocking");
        options.addArguments("--safebrowsing-disable-download-protection");
        Configuration.browserCapabilities = options;

        // 打开网页
        Selenide.open("https://example.com");

        // 点击下载链接
        Selenide.$(By.linkText("Download")).click();

        // 等待文件下载完成
        File downloadedFile = Selenide.waitUntil(() -> {
            File[] files = new File("下载文件保存路径").listFiles();
            if (files != null) {
                for (File file : files) {
                    if (!file.isDirectory()) {
                        return file;
                    }
                }
            }
            return null;
        }, 10000); // 最多等待10秒

        // 获取文件名
        String fileName = downloadedFile.getName();
        System.out.println("下载完成:" + fileName);
    }
}

请根据你的实际需求替换以下内容:

  • "https://example.com":替换为你要访问的网页链接。
  • By.linkText("Download"):替换为你要点击的下载链接的定位方式。
  • "下载文件保存路径":替换为你要保存下载文件的文件夹路径。

请注意,该示例代码使用了 Selenide 库来简化 Selenium WebDriver 的使用。你需要将 Selenide 相关的依赖添加到你的项目中

java selenide 等待文件下载完成但是我不知道下载的文件文件名是什么给出示例代码

原文地址: https://www.cveoy.top/t/topic/iQvU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录