我用C#在Selenium webdriver中写了一个自动化测试,其中一个步骤需要从服务器下载XLSX文件。如何验证文件是否下载成功并获得其名称?问候
0sgqnhkj1#
我发现了以下源代码的解决方案:
string currentPage = Browser.Current.Url; string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string downloadPath = Path.Combine(userPath, "Downloads"); DirectoryInfo dirInfo = new DirectoryInfo(downloadPath); if (!dirInfo.Exists) { dirInfo.Create(); } int directoryFiles = dirInfo.EnumerateFiles().Count(); string elementXpath = "//div[@id='myDiv']/div/div/div[@class='atalhos']/a[1]"; bool isFirefox = (Browser.Current as FirefoxDriver) != null; bool isChrome = (Browser.Current as ChromeDriver) != null; IWebDriver browserDriver = null; if (isChrome) { ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddUserProfilePreference("download.default_directory", downloadPath); chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true"); browserDriver = new ChromeDriver(chromeOptions); } else if (isFirefox) { FirefoxProfile profile = new FirefoxProfile(); profile.SetPreference("browser.download.folderList", 2); profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); browserDriver = new FirefoxDriver(profile); } browserDriver.Navigate().GoToUrl(currentPage); WebDriverWait wait = new WebDriverWait(browserDriver, TimeSpan.FromSeconds(15)); wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(elementXpath))); IWebElement elemento = browserDriver.FindElement(By.XPath(elementXpath)); elemento.Click(); Thread.Sleep(7000); dirInfo = new DirectoryInfo(downloadPath); int currentFiles = dirInfo.EnumerateFiles().Count(); Assert.Greater(currentFiles, directoryFiles);
zaq34kh62#
在下面的代码中,我已经取得了下载文件夹中的excel文件列表。如果你只有一个文件,那么使用file.name属性,或者如果你有多个文件,试试下面的代码。
private static string GetDownloadedFileName() { var fileName = ConfigurationManager.AppSettings["excelName"].ToString(); string pathUser=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string pathDownload = Path.Combine(pathUser, "Downloads"); DirectoryInfo downloadDir = new DirectoryInfo(pathDownload); FileInfo[] files = downloadDir.GetFiles("*.xls"); var file = files.Where(x => x.Name.Replace(" ", "") == fileName + ".xls").FirstOrDefault(); fileName = file.FullName; return fileName; }
2条答案
按热度按时间0sgqnhkj1#
我发现了以下源代码的解决方案:
zaq34kh62#
在下面的代码中,我已经取得了下载文件夹中的excel文件列表。如果你只有一个文件,那么使用file.name属性,或者如果你有多个文件,试试下面的代码。