简体   繁体   English

如何使用 selenium c# webdriver 重命名下载的文件

[英]How to rename downloaded file using selenium c# webdriver

In my web application which has some automation process to download the files from the website.在我的 Web 应用程序中,它具有一些从网站下载文件的自动化过程。 To achieve that I used selenium c# chrome driver.为此,我使用了 selenium c# chrome 驱动程序。

Sample code snippets示例代码片段

public void Download(string name,string pass)
{
    try
    {
        ChromeOptions options = new ChromeOptions();
        options.AddArguments("--proxy-server=http://192.168.5.62:8095");
        options.AddUserProfilePreference("safebrowsing.enabled", true);
        options.AddUserProfilePreference("disable-popup-blocking", "true");
        options.AddUserProfilePreference("download.default_directory",@"C:\Temp");

        using (var driver = new ChromeDriver(HostingEnvironment.ApplicationPhysicalPath, options)){

            //driver.findElement(By.xpath("//a/u[contains(text(),'Re-Submit')]")).click();
            driver.FindElementById("save").Click();                               
        }              
    }
    catch (Exception ex)
    {       
        Logger.LogWriter("LAS", ex, "CusDataLogic", "Download");
    }
}

above code (not complete code) works fine and save file properly.上面的代码(不是完整的代码)工作正常并正确保存文件。 But I need to rename that file downloading or after download.但我需要重命名该文件下载或下载后。 Have any possible way to rename that file?有任何可能的方法来重命名该文件吗?

Edited: Please don't mark this as a duplicate.已编辑:请不要将此标记为重复。 I'm asking for C#, not python.我要的是 C#,而不是 python。 I saw that question too.我也看到了这个问题。 but it not helped to me但这对我没有帮助

watching directory is not always good, because sometime saved filename is different than filename in URL.监视目录并不总是好的,因为有时保存的文件名与 URL 中的文件名不同。

go to chrome download page and loop until all download complete, you can see below how to select special element #shadow-root with CSS selector转到chrome下载页面并循环直到所有下载完成,您可以在下面看到如何使用CSS选择器选择特殊元素#shadow-root

using (var driver = new ChromeDriver(HostingEnvironment.ApplicationPhysicalPath, options)))
{
    //driver.findElement(By.xpath("//a/u[contains(text(),'Re-Submit')]")).click();
    driver.FindElementById("save").Click();

    // wait 5 second until download started
    Thread.Sleep(5000);

    // Go to chrome download page
    driver.Navigate().GoToUrl("chrome://downloads/");
    string oldName = "";
    bool downloadcomplete = false;
    string cssNames = "downloads-manager /deep/ downloads-item /deep/ [id='name']";
    string cssDlProgress = "downloads-manager /deep/ downloads-item /deep/ [class*='show-progress']";

    while (!downloadcomplete)
    {
        var progressElements = driver.FindElements(By.CssSelector(cssDlProgress));
        // check until no download progress bar
        if (progressElements.Count() == 0)
        {
            oldName = driver.FindElement(By.CssSelector(cssNames)).Text;
            downloadcomplete = true;
        }
        else
        {
            // download still in progress, wait.
            Thread.Sleep(1000);
        }
    }
    // download complete
    // remove downloaded file
    driver.FindElement(By.CssSelector("downloads-manager /deep/ downloads-item /deep/ [id='remove']")).Click();
    // rename
    File.Move(@"C:\Temp\" + oldName, @"C:\Temp\newname.ext");
}

The Snippet Below Will wait Until File downloaded Then return FilePath I Wrote this as an extension method :下面的代码段将等到文件下载然后返回 FilePath 我把它写成扩展方法:

public static string GetDonwloadedFileName(this IWebDriver driver)
{
    IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
    js.ExecuteScript("window.open()");
    var allWinowHandles = driver.WindowHandles;
    foreach (var winHandle in allWinowHandles)
    {
        //Switch to second window
        if (!winHandle.Equals(driver.CurrentWindowHandle))
        {
            driver.SwitchTo().Window(winHandle);
        }
    }
    // navigate to chrome downloads
    driver.Navigate().GoToUrl("chrome://downloads");
    IJavaScriptExecutor downloadWindowExecutor = (IJavaScriptExecutor)driver;
    // Wait for Download till 100% completion
    double percentageProgress = (double)0;
    while (percentageProgress != 100)
    {
        try
        {
            percentageProgress = (long)downloadWindowExecutor.ExecuteScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value");
            Thread.Sleep(100);
        }
        catch (Exception)
        {
            break;
        }
    }

    string fileTitle = (string)downloadWindowExecutor.ExecuteScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#show').getAttribute('title')");
    downloadWindowExecutor.ExecuteScript("window.close()");
    return fileTitle;
}

Then You can use file Path to rename it to whatever you need然后您可以使用文件路径将其重命名为您需要的任何内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C#中使用Selenium WebDriver下载文件时如何处理保留和丢弃选项按钮 - how to handle keep and discard option button when file is downloaded using selenium webdriver in c# 如何验证是否在Selenium Webdriver C#中下载文件 - How do I verify if a file is being downloaded in Selenium Webdriver C# 如何使用带有C#的Selenium WebDriver将数据写入Excel文件? - How to write data into an Excel file using Selenium WebDriver with C#? 如何使用Selenium Webdriver和C#创建日志文件? - How to create a log file using selenium webdriver and C#? 如何在C#中使用Selenium WebDriver执行本地javascript文件 - How to execute local javascript file using selenium webdriver in C# 如何使用 C# 在 Selenium WebDriver (Selenium 2) 中最大化浏览器窗口? - How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#? 在 C# 中使用 Autoit 在 selenium webdriver 中上传文件 - file upload in selenium webdriver using Autoit in C# 如何使用C#使用Selenium WebDriver知道URL? - How to know a URL is existing using Selenium WebDriver using C#? 如何从Selenium Webdriver C#中的文件中获取输入 - how to take input from file in selenium webdriver c# 如何使用Selenium WebDriver C#自动创建文本文件并在其中写入异常 - How to create Text file and write exceptions in it automatically using Selenium WebDriver C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM