以下是使用C#语言和Selenium3+Chrome来校验文件是否下载成功的示例代码:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.IO;

class Program
{
    static void Main(string[] args)
    
    {
        ChromeOptions options = new ChromeOptions();
        options.AddUserProfilePreference('download.default_directory', @"C:\Downloads"); // 设置下载文件夹路径
        options.AddUserProfilePreference('download.prompt_for_download', false); // 禁止弹出下载提示框

        IWebDriver driver = new ChromeDriver(options);

        driver.Navigate().GoToUrl("https://example.com/download/file.zip"); // 访问需要下载的文件链接

        // 等待文件下载完成,此处假设文件名为 file.zip
        string filePath = Path.Combine(@"C:\Downloads", 'file.zip');
        bool isFileDownloaded = false;
        int waitCount = 0;
        while (!isFileDownloaded && waitCount < 60) // 等待最多60秒
        {
            if (File.Exists(filePath))
            {
                isFileDownloaded = true;
            }
            else
            {
                System.Threading.Thread.Sleep(1000);
                waitCount++;
            }
        }

        // 校验文件是否下载成功
        if (isFileDownloaded)
        {
            Console.WriteLine('文件下载成功!');
        }
        else
        {
            Console.WriteLine('文件下载失败!');
        }

        driver.Quit();
    }
}

在上述代码中,我们使用ChromeOptions来设置Chrome浏览器的下载文件夹路径,并禁止弹出下载提示框。然后使用ChromeDriver来访问需要下载的文件链接。之后,我们使用while循环来等待文件下载完成,最多等待60秒。在循环中,我们检查文件是否已经存在于下载文件夹中,如果存在,则认为文件下载成功。最后,我们根据文件是否下载成功来输出相应的信息。

C# Selenium3+Chrome 文件下载成功校验 - 代码示例

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

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