2017-08-08 91 views
1

我在使用C#的Selenium webdriver中編寫了自動化測試,其中一個步驟需要從服務器下載XLSX文件。如何驗證文件是否已成功下載並獲取他的名字?如何檢查下載的文件Selenium WebDriver?

問候

+1

同時啓動webdriver的,給一個默認的下載路徑。下載文件後,檢查下載路徑中是否存在xlsx ... –

回答

1

我發現下面的源代碼的解決方案:

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); 
相關問題