使用Selenium WebDriver在自定义路径下载文件

时间:2015-10-30 11:02:04

标签: c# selenium selenium-chromedriver

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

2 个答案:

答案 0 :(得分:5)

希望对您有所帮助!

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 :(得分:1)

您需要一点技巧,以便可以在指定位置下载文件。 选项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;
        }

这对我有用,它断言下载是否成功并且可以重新运行,以及我们最后要删除文件。希望这会有所帮助!