C# 使用SeleniumWebDriver在自定义路径下载文件

C# 使用SeleniumWebDriver在自定义路径下载文件,c#,selenium,selenium-chromedriver,C#,Selenium,Selenium Chromedriver,我是selenium新手,我想在特定的自定义文件夹中下载带有selenium chrome web驱动程序的文件。默认情况下,文件在浏览器指定的下载路径中下载。任何人都可以建议在C#Selenium中以自定义路径下载文件的最佳解决方案。希望这对您有所帮助 var chromeOptions = new ChromeOptions(); chromeOptions.AddUserProfilePreference("download.default_directory", "Your_Path"

我是selenium新手,我想在特定的自定义文件夹中下载带有selenium chrome web驱动程序的文件。默认情况下,文件在浏览器指定的下载路径中下载。任何人都可以建议在C#Selenium中以自定义路径下载文件的最佳解决方案。

希望这对您有所帮助

var chromeOptions = new ChromeOptions();
 chromeOptions.AddUserProfilePreference("download.default_directory", "Your_Path");
 chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");
 chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
var driver = new ChromeDriver("Driver_Path", chromeOptions);

您需要进行一些黑客攻击,以便可以在指定位置下载该文件。 选项1:使用第三方工具,如AutoIt,它可以与Windows弹出窗口交互,您可以指定使用它的路径。 选项2:编写一个自定义方法,可以使用API进行下载

                    var downloadDocLink = webDriver.FindElement(By.XPath("{}")).GetAttribute("onclick");
                    string toBeSearched = "{string}"; //this string needs to be trimmed from the url
                    string downloadUrl = downloadDocLink.Substring(downloadDocLink.IndexOf(toBeSearched) + toBeSearched.Length);
                    var data = webDriver.DownloadByApiCall(downloadUrl);
                    var fileName = webDriver.FindElement(By.XPath("{Xpath}")).Text;

                    //Save result of report api call to file
                    var val = ConfigurationManager.AppSettings["OutputPath"];
                    var path = Environment.ExpandEnvironmentVariables(val);
                    var filePath = Path.Combine(path, fileName);

                    var dir = Path.GetDirectoryName(path);
                    Console.WriteLine($"Saving file with {data.Length} bytes to {path}.");
                    if (!Directory.Exists(dir))
                        Directory.CreateDirectory(dir);
                    File.WriteAllBytes(filePath, data);

                    //Ensure file was downloaded          
                    var exists = webDriver.FileExistsSpinWait(filePath);
                    Assert.IsTrue(exists, $"The downloaded report is not present in the download folder: \n{filePath}");

                    //Remove file and ensure deleted
                    File.Delete(filePath);
                    Assert.IsFalse(File.Exists(filePath));
通过API调用下载的帮助器方法

public static byte[] DownloadByApiCall(this IWebDriver driver, string apiCall)
        {
            var uri = new Uri(driver.Url);            
            var path = $"{url}/{apiCall}";

            byte[] data = null;
            try
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(path);

                webRequest.CookieContainer = new CookieContainer();
                foreach (var cookie in driver.Manage().Cookies.AllCookies)
                    webRequest.CookieContainer.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, string.IsNullOrWhiteSpace(cookie.Domain) ? uri.Host : cookie.Domain));

                var webResponse = (HttpWebResponse)webRequest.GetResponse();
                var ms = new MemoryStream();
                var responseStream = webResponse.GetResponseStream();
                responseStream.CopyTo(ms);
                data = ms.ToArray();
                responseStream.Close();
                webResponse.Close();
            }
            catch (WebException webex)
            {
                var errResp = webex.Response;
                using (var respStream = errResp.GetResponseStream())
                {
                    var reader = new StreamReader(respStream);
                    Assert.Fail($"Error getting file from the server({webex.Status} - {webex.Message}): {reader.ReadToEnd()}.");
                }
            }

            return data;
        }

这对我来说是可行的,它断言下载是否成功,它是否重新命名,以及我们是否最终删除了文件。希望这有帮助

如何获取下载文件的名称?或者在WebDriver启动后更改默认目录?@Slowaways我还没有尝试过,但我猜您在启动时选择了一个临时文件夹,每次下载后,您都可以枚举该目录以查找名称并(重新)移动该文件以准备下一次下载。