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

本文关键字:下载 文件 路径 自定义 SeleniumWebDriver 使用 | 更新日期: 2023-09-27 18:19:57

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

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

希望对您有所帮助!!

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;
        }

这对我来说很有效,它断言下载是否成功,是否可以重新运行,以及我们最终是否删除文件。希望这能有所帮助!