/// <summary> /// Launches the Selenium WebDriver driven browser specified in the Environments.cs file /// </summary> public IWebDriver LaunchBrowser(IWebDriver driver) { switch(this.environment.browser) { case "*firefox": _ffp = new FirefoxProfile(); _ffp.AcceptUntrustedCertificates = true; driver = new FirefoxDriver(_ffp); break; case "*iexplore": driver = new InternetExplorerDriver(); break; case "*googlechrome": driver = new ChromeDriver(); break; case "Android": capabilities = new DesiredCapabilities("android", "", null); capabilities.IsJavaScriptEnabled = true; driver = new RemoteWebDriver(new Uri(string.Format("http://{0}:{1}/hub", environment.host, environment.port)), capabilities); break; case "RemoteWebDriver": capabilities = DesiredCapabilities.Firefox(); var remoteAddress = new Uri(string.Format("http://{0}:{1}/wd/hub", environment.host, environment.port)); driver = new RemoteWebDriver(remoteAddress, capabilities); break; } return driver; }
//[Test] public void CanBlockInvalidSslCertificates() { FirefoxProfile profile = new FirefoxProfile(); profile.AcceptUntrustedCertificates = false; string url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("simpleTest.html"); IWebDriver secondDriver = null; try { secondDriver = new FirefoxDriver(profile); secondDriver.Url = url; string gotTitle = secondDriver.Title; Assert.AreNotEqual("Hello IWebDriver", gotTitle); } catch (Exception) { Assert.Fail("Creating driver with untrusted certificates set to false failed."); } finally { if (secondDriver != null) { secondDriver.Quit(); } } }
public void beforeClass() { Driver = new FirefoxDriver(); Selenium = new WebDriverBackedSelenium(Driver, Utils.baseUrl); Selenium.Start(); Selenium.WindowMaximize(); }
public void beforeClass() { Driver = new FirefoxDriver(); //Selenium = new WebDriverBackedSelenium(Driver, Utils.baseUrl); //Selenium.Start(); //Selenium.WindowMaximize(); Console.WriteLine("start browser!!!!"); }
static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://www.google.com"); Console.WriteLine(driver.Title); IWebElement query = driver.FindElement(By.Name("q")); query.SendKeys("Browserstack"); query.Submit(); Console.WriteLine(driver.Title); driver.Quit(); }
//constructors //methods public static void Setup(string url) { //FirefoxProfile profile = new FirefoxProfile(@"C:\Users\User\Documents\GitHub\MyProjects\QA\Telerik QA Academy exams\part I\SIE1a\SeleniumWebdriver"); BaseDriver = new FirefoxDriver(); //new FirefoxDriver(profile); //new ChromeDriver(@"D:\software\selenium\chrome"); //new InternetExplorerDriver(@"D:\software\selenium\ie"); Selenium = new WebDriverBackedSelenium(BaseDriver, BaseUrl); //Selenium.Start(); BaseDriver.Navigate().GoToUrl(url); BaseDriver.Manage().Window.Maximize(); }
public void SearchAndWait() { IWebDriver driver = new FirefoxDriver(); //Notice navigation is slightly different than the Java version //This is because 'get' is a keyword in C# driver.Navigate().GoToUrl("http://www.google.com/"); IWebElement query = driver.FindElement(By.Name("q")); query.SendKeys("FitNesse"); IWebElement button = driver.FindElement(By.Name("btnG")); button.Click(); Thread.Sleep(3000); driver.Quit(); }
/// <summary> /// Initiates the testing environment /// </summary> public TestBaidu() { if (!usingDriver) { if (selenium == null) { selenium = new DefaultSelenium(localIPAddress, port, targetExplorer, tagetURL); } } else { fp = new FirefoxProfile(); fp.SetPreference("dom.disable_open_during_load", false); driver = new FirefoxDriver(fp); } }
public void Log4netTest() { string testTime = DateTime.Now.ToString("s"); var driver = new FirefoxDriver(); driver.Navigate().GoToUrl("Http://www.baidu.com"); string expectedResult = "百度一下"; string actualResult = driver.FindElement(By.Id("su")).GetAttribute("value"); Console.WriteLine(actualResult); Assert.AreEqual(expectedResult,actualResult); // string fileName = "@d:\temp" + "\\" + System.DateTime.Now.ToString("yy-MM-dd") + "-log.log"; // 和PatternLayout一起使用FileAppender Console.WriteLine(expectedResult); //log4net.Config.BasicConfigurator.Configure(new log4net.Appender.FileAppender(new log4net.Layout.PatternLayout("%d[%t]%-5p %c [%x] - %m%n"),"testfile.log")); // using a FileAppender with an XMLLayout log4net.Config.BasicConfigurator.Configure(new log4net.Appender.FileAppender(new log4net.Layout.XmlLayout(), "2014testfile.xml")); }
/// <summary> /// BROWSER_TYPEの値によって起動するブラウザを変える /// (firefox以外は不安定) /// </summary> /// <param name="webDriver"></param> public static void SelectBrowser(ref IWebDriver webDriver) { switch (AppConfig.GetString(Config.BROWSER_TYPE)) { case "1": // FireFox FirefoxBinary firefoxBinary = new FirefoxBinary(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"); FirefoxProfile firefoxProfile = new FirefoxProfile(); webDriver = new FirefoxDriver(firefoxBinary, firefoxProfile); break; case "2": // Chrome webDriver = new ChromeDriver(); break; case "3": // IE // ブラウザのズームレベルを100%にしないと落ちる webDriver = new InternetExplorerDriver(); break; default: throw new OriginalException("BROWSER_TYPEが不正です。1~3の間で設定してください。"); } webDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); webDriver.Url = AppConfig.GetString(Config.TEST_URL); }
public void TestMethod1() { var driver = new FirefoxDriver(); Driver(driver); }
public void Dispose() { _firefoxDriver?.Dispose(); _firefoxDriver = null; }
public void TTestSelect() { var driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://t.hexun.com/default.htm"); var js_dispalyNull = string.Format("document.querySelector('#allnav').style.display=''"); ((IJavaScriptExecutor) driver).ExecuteScript(js_dispalyNull); // driver.FindElement(By.XPath("//*[@id='secnav11']/ul/li[4]/a")).Click(); driver.FindElement(By.XPath("//*[@id='allnav']/dl/dd[1]/a")).Click(); string exceptedResutl = "财经学者"; string actualResult = driver.FindElement(By.CssSelector("div.gsdrtit li.btnOver")).Text; Assert.AreEqual(exceptedResutl,actualResult); //driver.FindElement(By.XPath("div[@node-type='menu']")).Click(); // var clickEelement=driver.FindElement(By.XPath("//*[@id='SI_Top_Wrap']/div/div/div/div[1]/div[2]/a/i")); //var mouseOnAction = new OpenQA.Selenium.Interactions.Actions(driver); //mouseOnAction.MoveToElement(clickEelement); //mouseOnAction.Perform(); //clickEelement.Click(); }
public void TestMethod1() { IWebDriver driver = new FirefoxDriver(); //launch first website driver.Url = "https://www.amazon.com/"; //driver.Manage().Window.Maximize(); //perform search driver.FindElement(By.Id("twotabsearchtextbox")).SendKeys("Iphone11"); driver.FindElement(By.CssSelector("#nav-search-submit-text > input:nth-child(1)")).Click(); WebDriverWait waitForElement = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); try { waitForElement.Until(ExpectedConditions.ElementIsVisible(By.XPath("/html/body/div[1]/div[2]/div[1]/div[2]/div/span[3]/div[2]/div[1]/span/div/div/span[1]"))); Console.WriteLine("Search result displayed"); } catch (NoSuchElementException) { Console.WriteLine("Element was not found in current context page."); throw; } //open new tab Console.WriteLine("Open new tab"); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript("window.open('https://www.ebay.com','_blank');"); //perform search driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.FindElement(By.CssSelector("#gh-ac")).SendKeys("Iphone11"); driver.FindElement(By.CssSelector("#gh-btn")).Click(); WebDriverWait waitForElement1 = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); try { waitForElement1.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".srp-controls"))); Console.WriteLine("Search result displayed"); } catch (NoSuchElementException) { Console.WriteLine("Element was not found in current context page."); throw; } //back to first tab driver.SwitchTo().Window(driver.WindowHandles.First()); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); //copy test result IWebElement resultPanel = driver.FindElement(By.XPath("//h2[@class='a-size-mini a-spacing-none a-color-base s-line-clamp-2']")); IReadOnlyCollection <IWebElement> searchResults = resultPanel.FindElements(By.XPath("./a")); foreach (IWebElement result in searchResults) { String value = result.Text; Console.WriteLine(value); } driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); IWebElement resultPanel1 = driver.FindElement(By.XPath("//h3[@class='s-item__title']")); IReadOnlyCollection <IWebElement> searchResults1 = resultPanel1.FindElements(By.TagName("a")); foreach (IWebElement result1 in searchResults1) { String value1 = result1.Text; Console.WriteLine(value1); } driver.Quit(); }
public WebDriverClient Create() { IWebDriver webDriver; switch (browser) { case Browser.INTERNET_EXPLORER: var ieOptions = new InternetExplorerOptions(); if (headless) { throw new NotSupportedException("Headless mode for IE not available."); } if (acceptInsecureCertificates) { ieOptions.AcceptInsecureCertificates = true; } if (ignoreProtectedModeSettings) { ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; } LoadOptionsWithCapabilities(ref ieOptions); webDriver = new InternetExplorerDriver(ieOptions); break; case Browser.CHROME: var chromeOptions = new ChromeOptions(); if (headless) { chromeOptions.AddArguments("headless"); } if (acceptInsecureCertificates) { chromeOptions.AcceptInsecureCertificates = true; } LoadOptionsWithCapabilities(ref chromeOptions); webDriver = new ChromeDriver(chromeOptions); break; case Browser.FIREFOX: var firefoxOptions = new FirefoxOptions(); if (headless) { firefoxOptions.AddArguments("-headless"); } if (acceptInsecureCertificates) { firefoxOptions.AcceptInsecureCertificates = true; } LoadOptionsWithCapabilities(ref firefoxOptions); firefoxOptions.AcceptInsecureCertificates = true; webDriver = new FirefoxDriver(firefoxOptions); break; case Browser.ANDROIDMOBIL: throw new NotSupportedException("Please use CrossBrowserTesting Extension instead!"); default: throw new UnexpectedClientException("Unknown browser " + browser); } if (pageLoadTimeOut != null) { webDriver.Manage().Timeouts().PageLoad = new TimeSpan(0, 0, 0, pageLoadTimeOut.Value); } if (implicitWaitTimeOut != null) { webDriver.Manage().Timeouts().ImplicitWait = new TimeSpan(0, 0, 0, implicitWaitTimeOut.Value); } return(new WebDriverClient(webDriver)); }
public void TestMethod1() { IWebDriver driver; driver = new FirefoxDriver("C:\\Users\\Selenium Jars"); driver.Url = "http://www.youcandealwithit.com/"; driver.Manage().Window.Maximize(); IWebElement radio = driver.FindElement(By.XPath("//a[text()='Borrowers']")); Actions act = new Actions(driver); act.MoveToElement(radio).Build().Perform(); driver.FindElement(By.XPath("//*[text()='Calculators & Resources']")).Click(); string a = driver.FindElement(By.XPath("//*[text()='Calculators & Resources']")).Text; if (driver.FindElement(By.XPath("//*[text()='Calculators & Resources']")).Text.Contains(driver.Title)) { Console.WriteLine("Calculators & Resources Pass"); } else { Console.WriteLine("Calculators & Resources fails"); } Thread.Sleep(2000); driver.FindElement(By.LinkText("Calculators")).Click(); string b = driver.FindElement(By.LinkText("Calculators")).Text; if (b.Contains(driver.Title)) { Console.WriteLine(" Calculators Pass"); } else { Console.WriteLine(" Calculators fails"); } Thread.Sleep(2000); driver.FindElement(By.LinkText("Budget Calculator")).Click(); string c = driver.FindElement(By.LinkText("Budget Calculator")).Text; if (c.Contains(driver.Title)) { Console.WriteLine(" Budget Calculator Pass"); } else { Console.WriteLine("Budget Calculator fails"); } Thread.Sleep(2000); driver.FindElement(By.Id("food")).SendKeys("5000"); Thread.Sleep(1500); driver.FindElement(By.Id("clothing")).SendKeys("12000"); Thread.Sleep(1500); driver.FindElement(By.Id("shelter")).SendKeys("11000"); Thread.Sleep(1500); driver.FindElement(By.Id("monthlyPay")).SendKeys("50000"); Thread.Sleep(1500); driver.FindElement(By.Id("monthlyOther")).SendKeys("8000"); Thread.Sleep(10000); IWebElement exp = driver.FindElement(By.Id("totalMonthlyExpenses")); string expenses = exp.GetAttribute("value"); Console.WriteLine(expenses); IWebElement mpay = driver.FindElement(By.Id("monthlyPay")); string expense = mpay.GetAttribute("value"); if (Double.Parse(expenses) <= Double.Parse(expense)) { Console.WriteLine("YOU ARE WARREN WAFFET"); } else { Console.WriteLine("You are an VM"); } // driver.Close(); }
private void search_btn_Click(object sender, EventArgs e) { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("https://www.skyscanner.com"); // driver.Url = "https://www.skyscanner.com"; // driver.Manage().Window.Maximize(); // driver.Manage().Timeouts().ImplicitWait(TimeSpan.FromSeconds(10)); driver.FindElement(By.Id("fsc-origin-search")).SendKeys("Bodrum"); driver.FindElement(By.Id("fsc-destination-search")).SendKeys("Istanbul" + System.Windows.Forms.Keys.Enter); // System.Diagnostics.Process.Start("https://www.skyscanner.com.tr/"); /* //Get Request ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; string connectUrl = String.Format("https://www.skyscanner.com.tr/hotels?na=1&sd=2019-12-11&ed=2019-12-18&locale=en-GB"); WebRequest requestObjectGet = WebRequest.Create(connectUrl); requestObjectGet.Method = "GET"; HttpWebResponse responseObjectGet = null; responseObjectGet = (HttpWebResponse)requestObjectGet.GetResponse(); string stringResultTest = null; using (Stream stream = responseObjectGet.GetResponseStream()) { StreamReader sr = new StreamReader(stream); stringResultTest = sr.ReadToEnd(); sr.Close(); } //Post Request string strUrl = String.Format("https://www.skyscanner.com.tr/hotels?na=1&sd=2019-12-11&ed=2019-12-18&locale=en-GB"); WebRequest requestObjectPost = WebRequest.Create(strUrl); requestObjectPost.Method = "POST"; requestObjectPost.ContentType = "application/json"; string postData = null; using (var streamWriter = new StreamWriter (requestObjectPost.GetRequestStream())) { streamWriter.Write(postData); streamWriter.Flush(); streamWriter.Close(); var httpResponse = (HttpWebResponse)requestObjectPost.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result2 = streamReader.ReadToEnd(); } } */ /* var client1 = new RestClient("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsedates/v1.0/US/USD/en-US/SFO-sky/LAX-sky/2019-09-01?inboundpartialdate=2019-12-01"); //var request = new RestRequest(Method.GET); var request = new RestSharp.RestRequest(Method.GET); request.AddHeader("x-rapidapi-host", "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com"); request.AddHeader("x-rapidapi-key", "6bcc2d1861mshfa70f85a843bbe8p142731jsndc2ac6412dab"); RestSharp.IRestResponse response = client.Execute(request); var client = new RestClient("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0"); var request = new RestRequest(Method.POST); //var request = new RestSharp.RestRequest(Method.POST); request.AddHeader("x-rapidapi-host", "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com"); request.AddHeader("x-rapidapi-key", "6bcc2d1861mshfa70f85a843bbe8p142731jsndc2ac6412dab"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddParameter("application/x-www-form-urlencoded", "inboundDate=2019-09-10&cabinClass=business&children=0&infants=0&country=US¤cy=USD&locale=en-US&originPlace=SFO-sky&destinationPlace=LHR-sky&outboundDate=2019-09-01&adults=1", ParameterType.RequestBody); IRestResponse response = client.Execute(request); // IRestResponse response = (IRestResponse)client.Execute(request); */ }
private static IWebDriver CreateFirefoxBrowserInstance() { var fullFirefoxProfilePath = AppDomain.CurrentDomain.BaseDirectory + FIREFOX_PROFILE_PATH; fullFirefoxProfilePath = Path.GetFullPath(fullFirefoxProfilePath); var profile = new FirefoxProfile() //var profile = new FirefoxProfile { EnableNativeEvents = true, AcceptUntrustedCertificates = true, }; var downloadedFileDirectoryPath = AppDomain.CurrentDomain.BaseDirectory + "\\DownloadedFiles"; Directory.CreateDirectory(downloadedFileDirectoryPath); profile.SetPreference("browser.download.dir", downloadedFileDirectoryPath); profile.SetPreference( "browser.helperApps.neverAsk.saveToDisk", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/xlsx,text/csv,text/plain,text/html"); profile.SetPreference("browser.download.folderList", 2); // in order to prevent download manager to pop up, just enable 'old mode'. profile.SetPreference("browser.download.useToolkitUI", true); var fullFirefoxPortablePath = AppDomain.CurrentDomain.BaseDirectory + FIREFOX_PORTABLE_PATH; fullFirefoxPortablePath = Path.GetFullPath(fullFirefoxPortablePath); var fullFirefoxDriverPath = AppDomain.CurrentDomain.BaseDirectory + FIREFOX_DRIVER_PATH; fullFirefoxDriverPath = Path.GetFullPath(fullFirefoxDriverPath); var options = new FirefoxOptions { BrowserExecutableLocation = fullFirefoxPortablePath, Profile = profile }; options.SetPreference("--log", "error"); //options.AddAdditionalCapability("webdriver.firefox.marionette", false); var service = FirefoxDriverService.CreateDefaultService(fullFirefoxDriverPath, "geckodriver.exe"); IWebDriver ffBrowser = null; //Firefox internally locks port 7054 to prevent instantialization of multiple instances at the same time. //We are trying 5 times only to avoid an infinite while loop since there is no way to determine a number of tries other than trying if some number is "enough". //http://stackoverflow.com/questions/4296235/a-selenium-webdriver-exception for (var i = 0; i < 5; i++) { try { // infinite Timespan because of: CCNODLE-3312 (https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5071) ffBrowser = new FirefoxDriver(service, options, Timeout.InfiniteTimeSpan); ffBrowser.Navigate().GoToUrl("http://bing.com"); } catch (WebDriverException ex) { Console.WriteLine( $"Retrying after exception occured (port is locked by previous instance): {ex.Message}"); } if (ffBrowser != null) { break; } } return(ffBrowser); }
public void addPatient() { IWebDriver driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(link); Thread.Sleep(3000); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).SendKeys("root"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).SendKeys("password"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[5]/div[1]/app-button/button")).Click(); Thread.Sleep(5000); driver.FindElement(By.XPath("//div[contains(@class,'organization-container')]/div[2]")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class, 'nav-items flex-main-start')]/div[2]")).Click(); Thread.Sleep(8000); driver.FindElement(By.XPath("//div[contains(@class,'add-wrapper flex-cross-center clickable ng-star-inserted')]")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class,'body-wrapper')]/div[1]/app-button/button")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'icon-wrapper flex-center')]")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class,'add-wrapper flex-cross-center clickable ng-star-inserted')]")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'body-wrapper')]/div[2]/app-button/button")).Click(); Thread.Sleep(2000); Random rnd = new Random(); int rndNum = rnd.Next(10000); var rndfirstName = new List <string> { "Mark", "Carlo", "Kim", "Ashe" }; var rndlastName = new List <string> { "Larned", "Shu", "Cartwright", "Ketchum" }; int index = rnd.Next(rndfirstName.Count); int index2 = rnd.Next(rndlastName.Count); var firstName = rndfirstName[index]; rndfirstName.RemoveAt(index); var lastName = rndlastName[index]; rndlastName.RemoveAt(index); driver.FindElement(By.XPath("//app-input[contains(@formcontrolname, 'id_number')]/div/input")).SendKeys("" + rndNum); driver.FindElement(By.XPath("//app-input[contains(@formcontrolname, 'first_name')]/div/input")).SendKeys("" + firstName); driver.FindElement(By.XPath("//app-input[contains(@formcontrolname, 'middle_name')]/div/input")).SendKeys("B."); driver.FindElement(By.XPath("//app-input[contains(@formcontrolname, 'last_name')]/div/input")).SendKeys("" + lastName); driver.FindElement(By.XPath("//app-input[contains(@formcontrolname, 'email_address')]/div/input")).SendKeys("" + firstName + lastName + rndNum + "@mail.com"); driver.FindElement(By.XPath("//app-input[contains(@formcontrolname, 'mobile_number')]/div/input")).SendKeys("987654321"); driver.FindElement(By.XPath("//button[contains(@class,'label btnPrimary')]")).Click(); Thread.Sleep(2000); driver.Close(); driver.Quit(); }
public static IWebDriver GetFirefoxDriver() { IWebDriver driver = new FirefoxDriver(); return(driver); }
public void OpenFirefox() { driver = new FirefoxDriver(); }
private static void Checkout(KeyValueConfigurationCollection settings) { log.Info("Checkout started!!"); //Get value from AppSettings string pathToCurrentUserProfilesDirectory = Environment.ExpandEnvironmentVariables("%APPDATA%") + @"\Mozilla\Firefox\Profiles"; string[] pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfilesDirectory); string pathtoDefaultProfile = pathsToProfiles[0]; if (pathToCurrentUserProfile != string.Empty) { pathtoDefaultProfile = pathToCurrentUserProfile; } log.Info("Profile Path=" + pathtoDefaultProfile); if (pathsToProfiles.Length != 0) { FirefoxProfile profile = new FirefoxProfile(pathtoDefaultProfile); profile.SetPreference("browser.tabs.loadInBackground", true); FirefoxOptions options = new FirefoxOptions(); options.Profile = profile; var driverService = FirefoxDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); FirefoxDriver driver = new FirefoxDriver(driverService, options); WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5)); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; vars = new Dictionary <string, object>(); try { //Get value from AppSettings if (goToUrl == string.Empty) { driver.Navigate().GoToUrl("https://www.bigbasket.com/basket/"); } else { driver.Navigate().GoToUrl(goToUrl); } //driver.Manage().Window.Size = new System.Drawing.Size(1659, 917); driver.Manage().Window.Maximize(); driver.FindElement(By.CssSelector("#checkout > .icon")).Click(); log.Info("Checkout click Successful!!"); Thread.Sleep(5000); try { IWebElement slotButton = driver.FindElement(By.CssSelector(".slotmodal-btn-confirm")); Thread.Sleep(5000); IWebElement slotcontent = driver.FindElement(By.XPath("//p[@id=\'slotContent\']")); Thread.Sleep(5000); vars["ConfirmationMsg"] = slotcontent.Text; string txt = vars["ConfirmationMsg"].ToString(); if (txt.Length != 0) { log.Info(txt); Actions act = new Actions(driver); act.MoveToElement(slotButton).Click().Perform(); if (txt.ToLower().Contains("unfortunately")) { log.Info("No slots available"); } else { StopCheckout(settings); log.Info("Checkout Stopped"); SendSMS("Might have been successful, please check", settings); } } else { log.Info(txt); StopCheckout(settings); log.Info("Checkout Stopped"); SendSMS("Might have been successful, please check", settings); } } catch (Exception ex) { StopCheckout(settings); log.Info("Checkout Stopped"); SendSMS("Might have been successful, please check", settings); log.Error(ex.Message); } log.Info("Checkout ends!!"); driver.Close(); driver.Quit(); } catch (Exception ex) { StopCheckout(settings); log.Info("Checkout Stopped"); SendSMS("has an error", settings); log.Error(ex.Message); driver.Close(); driver.Quit(); } } else { log.Info("No profile presents"); } }
/// <summary> /// Create a new driver for the given browser type. /// </summary> /// <param name="browser">The browser to create a driver for.</param> /// <returns>The driver created.</returns> protected IWebDriver InitDriver(BrowserType browser) { Driver?.Quit(); IWebDriver driver; switch (browser) { case BrowserType.Chrome: ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddArgument("--disable-extension"); chromeOptions.AddArgument("--no-sandbox"); chromeOptions.AddArgument("--disable-infobars"); chromeOptions.AddUserProfilePreference("credentials_enable_service", false); chromeOptions.AddUserProfilePreference("profile.password_manager_enabled", false); driver = new ChromeDriver(Directory.GetCurrentDirectory(), chromeOptions); break; case BrowserType.InternetExplorer: InternetExplorerOptions ieCaps = new InternetExplorerOptions { EnablePersistentHover = true, EnsureCleanSession = true, EnableNativeEvents = true, IgnoreZoomLevel = true, IntroduceInstabilityByIgnoringProtectedModeSettings = true, RequireWindowFocus = false }; driver = new InternetExplorerDriver(Directory.GetCurrentDirectory(), ieCaps); break; case BrowserType.Firefox: FirefoxOptions ffOptions = new FirefoxOptions(); ffOptions.AddArgument("-safe-mode"); driver = new FirefoxDriver(Directory.GetCurrentDirectory(), ffOptions); break; case BrowserType.Edge: EdgeOptions edgeOptions = new EdgeOptions { UseInPrivateBrowsing = true, UnhandledPromptBehavior = UnhandledPromptBehavior.Accept }; driver = new EdgeDriver(Directory.GetCurrentDirectory(), edgeOptions); break; case BrowserType.HeadlessChrome: ChromeOptions headlessChromeOptions = new ChromeOptions(); headlessChromeOptions.AddArgument("--disable-extension"); headlessChromeOptions.AddArgument("--headless"); headlessChromeOptions.AddArgument("--no-sandbox"); headlessChromeOptions.AddArgument("--disable-infobars"); headlessChromeOptions.AddUserProfilePreference("credentials_enable_service", false); headlessChromeOptions.AddUserProfilePreference("profile.password_manager_enabled", false); driver = new ChromeDriver(Directory.GetCurrentDirectory(), headlessChromeOptions); break; default: throw new ArgumentException($"Unknown browser: {browser}"); } driver.Manage().Window.Maximize(); driver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(2); return(driver); }
public IWebDriver GetWebDriver(string browser, string Url = null) { IWebDriver driver; if (string.IsNullOrEmpty(Url)) { Url = $@"https://{Config.AuthenticateUserName}:{Config.AuthenticatePassword}@{Config.SiteUrl}/site"; } switch (browser.ToLower()) { case "chrome": { ChromeDriverService service = ChromeDriverService.CreateDefaultService(); ChromeOptions options = new ChromeOptions(); options.AddArgument("--disable-infobars"); options.AddArguments("--disable-extensions"); driver = new ChromeDriver(service, options, TimeSpan.FromSeconds(120)); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(Url); break; } case "ie": { InternetExplorerDriverService service = InternetExplorerDriverService.CreateDefaultService(); InternetExplorerOptions options = new InternetExplorerOptions(); driver = new InternetExplorerDriver(service, options, TimeSpan.FromSeconds(120)); driver.Manage().Window.Maximize(); driver.Navigate().Refresh(); driver.Navigate().GoToUrl(Url); break; } case "firefox": { FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(); FirefoxOptions options = new FirefoxOptions(); options.SetPreference("browser.tabs.remote.autostart", false); options.SetPreference("browser.tabs.remote.autostart.1", false); options.SetPreference("browser.tabs.remote.autostart.2", false); driver = new FirefoxDriver(service, options, TimeSpan.FromSeconds(120)); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(Url); break; } //case "edge": // { // EdgeDriverService service = EdgeDriverService.CreateDefaultService(); // EdgeOptions options = new EdgeOptions(); // options.AddAdditionalCapability("nativeEvents", true); // options.AddAdditionalCapability("acceptSslCerts", true); // options.AddAdditionalCapability("javascriptEnabled", true); // options.AddAdditionalCapability("INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS", true); // options.AddAdditionalCapability("takes_screenshot", true); // options.AddAdditionalCapability("cssSelectorsEnabled", true); // driver = new EdgeDriver(service, options, TimeSpan.FromSeconds(120)); // break; // } default: throw new ArgumentException($"Browser Option {browser} Is Not Valid - Use Chrome, Firefox or IE Instead"); } return(driver); }
private void BotMain() { try { List <string> infos = lireFichier("data");//On récupère les données if (infos[0] == "Erreur") { return; } //On attend wait(Int32.Parse(infos[9]), Int32.Parse(infos[10])); this.m_start.Text = "Bot is running"; FirefoxDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("https://www.neobux.com/m/l/?vl=1062F974ABAAB97FF378E7C9964A55B1");//on se rend sur la page //On se connecte driver.FindElementById("Kf1").SendKeys(infos[0]); //username driver.FindElementById("Kf2").SendKeys(infos[1]); //password wait(10, 10); driver.FindElementById("botao_login").Click(); //On attend wait(10, 10); //On va sur la page des pubs driver.FindElementByXPath("//td[@valign='bottom']/table/tbody/tr/td/a[@class='button green'][1]").Click(); //On comtpe les pubs int nbAdds = 0; for (int i = 1; i != 0; i++) { if (estPresent(driver, By.Id("da" + i.ToString() + "a"))) { nbAdds += 1; } else { break; } } //On adapte notre bar this.progressBar.Maximum = nbAdds; //On peut commencer if (nbAdds != 0)//Si il y a des pubs { for (int i = 1; i <= nbAdds; i++) { int j = 0; if (Int32.TryParse(infos[2], out j)) //On convertit en int { if (!estPresent(driver, By.XPath("//div[@id='da" + i.ToString() + "a']/div[@class='ad0']"))) //Si l'annonce n'est pas de type "transparent" (quelle n'a aps déja été vue) { //On commence par attendre if (j < 1) { wait(0, j + 1); } else { wait(j - 1, j + 1); } //On clique clicker(driver, ("da" + i.ToString() + "a"), ("//span[@id='da" + i.ToString() + "c']/a[1]"), "//table[@id='o1'][@style='display:none;']", Int32.Parse(infos[2])); //On voit pour une pause if (infos[7] == "1") { pause(infos); } } } else { erreur("ERROR : The speed in DATA file does not correspond."); return; } //On a fait un tour de boucle, on augmente notre Barre de progression progressBar.PerformStep(); } } //On en a finit avec les pubs on passe aux addprizes driver.Navigate().Refresh(); if (estPresent(driver, By.XPath("//a[@class='button small2 blue']/span[1]")) && infos[3] == "1") { driver.FindElementByXPath("//a[@class='button small2 blue']/span[1]"); int nb_adprize = Int32.Parse(driver.FindElementByXPath("//span[@id='ap_hct']/a[1]").Text); this.progressBar.Value = 0; this.progressBar.Maximum = nb_adprize; for (int i = 1; i <= nb_adprize; i++) { clicker(driver, "ap_hct", "0", "//table[@id='prm0'][@style='padding-bottom:5px;display:none;']", Int32.Parse(infos[2])); this.progressBar.PerformStep(); } } //On ferme les navigateurs driver.Close(); if (infos[8] == "1") { Process[] AllProcesses = Process.GetProcesses(); foreach (var process in AllProcesses) { if (process.MainWindowTitle != "") { string s = process.ProcessName.ToLower(); if (s == "firefox") { process.Kill(); } } } } //On a finit ! m_start.Text = "Finnished !"; //On ferme si nécessaire if (infos[6] == "1") { Application.Exit(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private void btnDoMK_Click(object sender, EventArgs e) { SaveFileDialog saveDialog = new SaveFileDialog(); // chọn đường dẫn lưu ảnh chụp màn hình saveDialog.Filter = "PNG Files (.png)|*.png|All Files (*.*)|*.*"; saveDialog.FilterIndex = 1; // if (saveDialog.ShowDialog() == DialogResult.OK) { FirefoxDriver firefoxDriver; firefoxDriver = new FirefoxDriver(); firefoxDriver.Manage().Window.Maximize(); firefoxDriver.Url = "http://online.hcmute.edu.vn/"; firefoxDriver.Navigate(); // bắt sự kiện click vào button đăng nhập try { // tìm đối tượng theo ID var btnDangNhap = firefoxDriver.FindElementById("ctl00_lbtDangnhap"); //đang cố ý để erro để bắt try cat //click vào button đăng nhập btnDangNhap.Click(); } catch (Exception ex) { DialogResult dlr = MessageBox.Show("Có lỗi, bạn có muốn tiếp tục. \n" + ex, "Thông báo", MessageBoxButtons.YesNo); if (dlr == DialogResult.Yes) { // lưu ảnh chụp màn hình cuối cùng(đoạn này copy hoàn toàn trên Google) screenBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); screenGraphics = Graphics.FromImage(screenBitmap); screenGraphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); screenBitmap.Save(saveDialog.FileName, ImageFormat.Png); firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở frmKTChucNang fr1 = new frmKTChucNang(); fr1.Show(); } else { firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở Application.Exit(); //đóng giao diện } } try { //tìm đến chỗ ô tên đăng nhập var txtTenDangNhap = firefoxDriver.FindElementByXPath("//*[@id=\"ctl00_ContentPlaceHolder1_ctl00_ctl00_txtUserName\"]"); //gõ tên đăng nhập vào txtTenDangNhap.SendKeys("15110231"); Thread.Sleep(1000); // ngủ 1 giây } catch (Exception ex1) { DialogResult dlr = MessageBox.Show("Có lỗi, bạn có muốn tiếp tục. \n" + ex1, "Thông báo", MessageBoxButtons.YesNo); if (dlr == DialogResult.Yes) { // lưu ảnh chụp màn hình cuối cùng(đoạn này copy hoàn toàn trên Google) screenBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); screenGraphics = Graphics.FromImage(screenBitmap); screenGraphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); screenBitmap.Save(saveDialog.FileName, ImageFormat.Png); //đóng hoàn toàn ứng dụng firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở frmKTChucNang fr1 = new frmKTChucNang(); fr1.Show(); } else { firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở Application.Exit(); //đóng giao diện } } int x = 0; while (x < 999999) { try { //tìm đến ô mật khẩu var txtMK = firefoxDriver.FindElementByXPath("//*[@id=\"ctl00_ContentPlaceHolder1_ctl00_ctl00_txtPassword\"]"); //gõ mật khẩu vào txtMK.SendKeys(XLMK(x)); //tìm đến button đăng nhập và nhấn vào nó var btn1 = firefoxDriver.FindElementByXPath("//*[@id=\"ctl00_ContentPlaceHolder1_ctl00_ctl00_btLogin\"]"); btn1.Click(); //tìm đến chỗ THÔNG TIN CÁ NHÂN và nhấn vào nó var btn2 = firefoxDriver.FindElementById("ctl00_ContentPlaceHolder1_ctl00_ctl00_lnkInfo"); btn2.Click(); firefoxDriver.Manage().Window.Minimize(); Thread.Sleep(2000); MessageBox.Show("Mật khẩu là: " + XLMK(x)); break; } catch (Exception er) { x++; } } } }
static void Main(string[] args) { try { ObjectLibrary.Helper hlpr = new ObjectLibrary.Helper(); string batchfile = ConfigurationManager.AppSettings["batchfile"]; string brwsr = ConfigurationManager.AppSettings["browser"]; string testfolder = ConfigurationManager.AppSettings["testfolder"]; string ffbin = ConfigurationManager.AppSettings["ffbin"]; DataTable dtbatch = hlpr.dtFromExcelFile(batchfile, "BatchSheet"); IWebDriver drv = null; IWebElement elem = null; /// List<IWebElement> Iwebcollection = null; System.Collections.ObjectModel.ReadOnlyCollection<IWebElement> Iwebcollection = null; foreach (DataRow dr in dtbatch.Rows) { string flagexec = dr["executeflag"].ToString(); if (flagexec.ToLower() == "y") { string scriptname = Path.Combine(testfolder, dr["scriptname"].ToString()); #region SCRIPTEXECUTION DataTable dtscript = hlpr.dtFromExcelFile(scriptname, "Sheet1"); WebDriverWait wait = null; foreach (DataRow drscript in dtscript.Rows) { if (drscript["Comment"].ToString() != null) { string comment = drscript["Comment"].ToString(); } string keyword = drscript["Keyword"].ToString(); string url = drscript["URL"].ToString(); string index = drscript["Index"].ToString(); string fieldname = drscript["FieldName"].ToString(); string subcontrol = drscript["Subcontrol"].ToString(); string searchby = drscript["SearchBy"].ToString(); string searchvalue = drscript["SearchValue"].ToString(); string datavalue = drscript["DataValue"].ToString(); string testcaseid = drscript["testcaseID"].ToString(); string dynatext = drscript["DynaText"].ToString(); switch (keyword.ToLower()) { #region LaunchBrowser case "launchbrowser": { try { if (brwsr.ToLower() == "ie") { drv = new InternetExplorerDriver(); wait = new WebDriverWait(drv, TimeSpan.FromMinutes(5.00)); } else if (brwsr.ToLower() == "firefox") { FirefoxBinary bin = new FirefoxBinary(ffbin); FirefoxProfile ffprofile = new FirefoxProfile(); drv = new FirefoxDriver(bin,ffprofile); wait = new WebDriverWait(drv, TimeSpan.FromMinutes(5.00)); } else if (brwsr.ToLower() == "chrome") { drv = new ChromeDriver(); wait = new WebDriverWait(drv, TimeSpan.FromMinutes(5.00)); } } catch (Exception ex) { hlpr.LogtoTextFile("Exception from keyword launchbrowser: " + ex.ToString()); } break; } #endregion LaunchBrowser #region Navigate case "navigatetourl": { try { drv.Navigate().GoToUrl(url); } catch (Exception ex) { hlpr.LogtoTextFile("Exception from keyword navigatetourl: " + ex.ToString()); } break; } #endregion Navigate #region ClickLink case "clicklink": { try { hlpr.LogtoTextFile("Looking up for " + fieldname); switch (searchby.ToLower()) { case "linktext": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.LinkText(searchvalue))); elem.Click(); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "partiallinktext": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.PartialLinkText(searchvalue))); elem.Click(); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "divtitle": { try { drv.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(40)); Iwebcollection = drv.FindElements(By.TagName("div")); foreach (IWebElement inddivelem in Iwebcollection) { // inddivelem.FindElement(By.TagName(searchvalue)) // elem = wait.Until(ExpectedConditions.ElementExists(By.TagName(searchvalue))); // elem = wait.Until(ExpectedConditions.ElementExists(By.TagName("div"))); if (inddivelem.GetAttribute("title") == searchvalue) { inddivelem.Click(); break; } } } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } } } catch (Exception ex) { hlpr.LogtoTextFile("Exception from keyword clicklink " + ex.Message); } break; } #endregion Clicklink #region EnterText case "entertext": { try { hlpr.LogtoTextFile("Looking up for " + fieldname); switch (searchby.ToLower()) { case "name": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.Name(searchvalue))); enterdata(elem, datavalue,dynatext); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "id": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.Id(searchvalue))); enterdata(elem, datavalue, dynatext); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "xpath": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.XPath(searchvalue))); enterdata(elem, datavalue, dynatext); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } } } catch (Exception ex) { hlpr.LogtoTextFile("Exception from keyword clicklink " + ex.Message); } break; } #endregion EnterText #region EnterTextArea case "entertextarea" : { try { hlpr.LogtoTextFile("Looking up for " + fieldname); switch (searchby.ToLower()) { case "name": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.Name(searchvalue))); enterdata(elem, datavalue, dynatext); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "id": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.Id(searchvalue))); enterdata(elem, datavalue, dynatext); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "xpath": { try { elem = wait.Until(ExpectedConditions.ElementExists(By.XPath(searchvalue))); enterdata(elem, datavalue, dynatext); } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } } } catch (Exception ex) { hlpr.LogtoTextFile("Exception from keyword clicklink " + ex.Message); } break; } #endregion #region ClickButton case "clickbutton": { hlpr.LogtoTextFile("Looking up for " + fieldname); try { switch (searchby.ToLower()) { case "name": { try { if (datavalue == "1") { elem = wait.Until(ExpectedConditions.ElementExists(By.Name(searchvalue))); elem.Click(); } } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "id": { try { if (datavalue == "1") { elem = wait.Until(ExpectedConditions.ElementExists(By.Id(searchvalue))); elem.Click(); } } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "xpath": { try { if (datavalue == "1") { elem = wait.Until(ExpectedConditions.ElementExists(By.XPath(searchvalue))); elem.Click(); } } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } case "value": { try { drv.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(40)); Iwebcollection = drv.FindElements(By.TagName("input")); foreach (IWebElement inddivelem in Iwebcollection) { // inddivelem.FindElement(By.TagName(searchvalue)) // elem = wait.Until(ExpectedConditions.ElementExists(By.TagName(searchvalue))); elem = wait.Until(ExpectedConditions.ElementExists(By.TagName("input"))); if (inddivelem.GetAttribute("value") == searchvalue) { inddivelem.Click(); break; } } } catch (Exception ex) { hlpr.LogtoTextFile("Unable to find " + searchby + " using " + searchvalue + " " + ex.Message); } break; } } } catch (Exception ex) { hlpr.LogtoTextFile("Exception from keyword clicklink " + ex.Message); } break; } #endregion ClickButton #region SelectRadioButton #endregion SelectRadioButton #region VerifyTextonPage case "verifytextonpage": { string acttext = drv.FindElement(By.TagName("body")).Text; hlpr.counter = 1; hlpr.AreEqual(testcaseid, fieldname, "text", searchvalue, acttext, ObjectLibrary.Helper.CompareType.contains); break; } #endregion VerifyTextPage #region VerifyTable #endregion VerifyTable default: { hlpr.LogtoTextFile("Not a Valid keyword " + keyword); break; } } } #endregion SCRIPTEXECUTION } System.Threading.Thread.Sleep(5000); if (drv != null) { drv.Quit(); } } hlpr.LogtoFileCSV(hlpr.dtRep); Console.WriteLine("Exceution Complete Check Results at Configured Paths"); System.Threading.Thread.Sleep(3000); } catch (Exception ex) { Console.WriteLine("Exception in Framewok " + ex.Message); } }
public virtual void InitializeTest() { br = new FirefoxDriver(); wait = new SafeWebDriverWait(br, DefaultTimeOut); br.Navigate().GoToUrl(url); }
static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); driver.Url = "http://store.demoqa.com/"; }
/// <summary> /// Method to create the driver based on string values /// that define the configuration to be tested /// </summary> /// <param name="browserType">browser under test</param> /// <param name="browserVersion">browser version under test</param> /// <param name="operatingSystem">operating system under test</param> /// <param name="environment">test environment</param> /// <param name="runLocation">determines if the test is to be executed remotely or locally</param> public void createDriver(string browserType, string browserVersion, string operatingSystem, string environment, string runLocation) { //Set the browser under test setBrowserType(browserType); //Set the browser version under test setBrowserVersion(browserVersion); //Set the operating system under test setOperatingSystem(operatingSystem); //Set the environment under test setEnvironment(environment); //Set the run location (e.g. local or remote) setRunLocation(runLocation); //********************************************** //********************************************** //*************** ****************** //*************** RUN LOCALLY ****************** //*************** ****************** //********************************************** //********************************************** if (runLocation.ToLower().Equals("local")) { //Determine the type of browser to test switch (browserType.ToLower()) { //Test the chrome browser case "chrome": //driver = new ChromeDriver(@"C:\selenium-dotnet-2.43.1\drivers"); driver = new ChromeDriver(@"C:\Users\temp\Documents\Visual Studio 2013\Projects\Selenium_CS\Selenium_CS\Orasi\Drivers"); break; //Test the firefox browser case "firefox": driver = new FirefoxDriver(); break; default: Assert.IsTrue(driver != null, "The browser type " + browserType + " is not supported by this Selenium setup."); break; } } //********************************************** //********************************************** //*************** ***************** //*************** RUN REMOTELY ***************** //*************** ***************** //********************************************** //********************************************** else { Uri uri = new Uri(prop.get("BLUESOURCE_URL_" + getEnvironment().ToUpper(), "1")); driver = new ScreenShotRemoteWebDriver(uri, caps); Assert.IsTrue(driver != null, "The browser type " + browserType + " is not supported by this Selenium setup."); } //Set the driver - this will be inherited by the test class setDriver(driver); //Maximize the browser window driver.Manage().Window.Maximize(); //Delete all cookies driver.Manage().Cookies.DeleteAllCookies(); }
public Browser() { driver = new FirefoxDriver(); }
public void Setup() { firefox = new FirefoxDriver(); }
private static RemoteWebDriver getFirefoxDriver() { RemoteWebDriver driver = new FirefoxDriver(); return(driver); }
public void Setup() { _driver = new FirefoxDriver(); _driver.Url = "http://motherboard.vice.com/read/i-built-a-botnet-that-could-destroy-spotify-with-fake-listens"; }
public void Setup() { Driver = new FirefoxDriver("C:\\Selenium\\"); Driver.Manage().Window.Maximize(); Driver.Navigate().GoToUrl("https://demowf.aspnetawesome.com/"); }
public void ShouldBeAbleToStartANamedProfile() { FirefoxProfile profile = new FirefoxProfileManager().GetProfile("default"); if (profile != null) { IWebDriver firefox = new FirefoxDriver(profile); firefox.Quit(); } else { Assert.Ignore("Skipping test: No profile named \"default\" found."); } }
public void adminChangeLanguage() { IWebDriver driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(link); Thread.Sleep(3000); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).SendKeys("root"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).SendKeys("password"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[5]/div[1]/app-button/button")).Click(); Thread.Sleep(5000); driver.FindElement(By.XPath("//div[contains(@class,'organization-container')]/div[2]")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class, 'nav-items flex-main-start')]/div[3]")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class,'main-container clickable')]/div")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//span[contains(text(),'Finnish')]")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'body-wrapper')]/div[1]/div[contains(@class,'content-container ng-star-inserted')]/div/div[contains(@class,'button-container flex-main-end')]/app-button")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'main-container clickable')]/div")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//span[contains(text(),'Norja')]")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'body-wrapper')]/div[1]/div[contains(@class,'content-container ng-star-inserted')]/div/div[contains(@class,'button-container flex-main-end')]/app-button")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'main-container clickable')]/div")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//span[contains(text(),'Svensk')]")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'body-wrapper')]/div[1]/div[contains(@class,'content-container ng-star-inserted')]/div/div[contains(@class,'button-container flex-main-end')]/app-button")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'main-container clickable')]/div")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//span[contains(text(),'Engelska')]")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'body-wrapper')]/div[1]/div[contains(@class,'content-container ng-star-inserted')]/div/div[contains(@class,'button-container flex-main-end')]/app-button")).Click(); Thread.Sleep(2000); driver.Close(); driver.Quit(); }
void NavigateByXpath(string XPath) { SaveFileDialog saveDialog = new SaveFileDialog(); // chọn đường dẫn lưu ảnh chụp màn hình saveDialog.Filter = "PNG Files (.png)|*.png|All Files (*.*)|*.*"; saveDialog.FilterIndex = 1; // if (saveDialog.ShowDialog() == DialogResult.OK) { //đóng giao diện this.Hide(); //khởi động trình duyệt firefoxDriver = new FirefoxDriver(); //phóng to trình duyệt ra toàn màn hình this.firefoxDriver.Manage().Window.Maximize(); //truy cập trực tiếp tới địa chỉ tuyệt đối của trang online firefoxDriver.Url = "https://online.hcmute.edu.vn/"; firefoxDriver.Navigate(); try { // tìm đối tượng theo ID var btnDangNhap = firefoxDriver.FindElementById("ctl00_lbtDangnhap");//đang cố ý để erro để bắt try cat //click vào button đăng nhập btnDangNhap.Click(); //tìm đến chỗ ô tên đăng nhập var txtTenDangNhap = firefoxDriver.FindElementByXPath("//*[@id=\"ctl00_ContentPlaceHolder1_ctl00_ctl00_txtUserName\"]"); //gõ tên đăng nhập vào txtTenDangNhap.SendKeys("15110231"); Thread.Sleep(1000); // ngủ 1 giây //tìm đến ô mật khẩu var txtMK = firefoxDriver.FindElementByXPath("//*[@id=\"ctl00_ContentPlaceHolder1_ctl00_ctl00_txtPassword\"]"); //gõ mật khẩu vào txtMK.SendKeys("000030"); Thread.Sleep(1000); //tiếp tục ngủ 1 giây để xem kết quả (Sẽ tắt khi mạng yếu) //tìm đến button đăng nhập và nhấn vào nó var btn1 = firefoxDriver.FindElementByXPath("//*[@id=\"ctl00_ContentPlaceHolder1_ctl00_ctl00_btLogin\"]"); btn1.Click(); //tìm đến chỗ THÔNG TIN CÁ NHÂN và nhấn vào nó var btn2 = firefoxDriver.FindElementByXPath(XPath); btn2.Click(); Thread.Sleep(1000); // lại ngủ 1 giây // lưu ảnh chụp màn hình cuối cùng(đoạn này copy hoàn toàn trên Google) screenBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); screenGraphics = Graphics.FromImage(screenBitmap); screenGraphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); screenBitmap.Save(saveDialog.FileName, ImageFormat.Png); DialogResult dlr = MessageBox.Show("Xong , bạn có muốn tiếp tục. \n", "Thông báo", MessageBoxButtons.YesNo); if (dlr == DialogResult.Yes) { // lưu ảnh chụp màn hình cuối cùng(đoạn này copy hoàn toàn trên Google) screenBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); screenGraphics = Graphics.FromImage(screenBitmap); screenGraphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); screenBitmap.Save(saveDialog.FileName, ImageFormat.Png); //đóng hoàn toàn ứng dụng firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở frmKTChucNang fr1 = new frmKTChucNang(); fr1.Show(); } else { firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở Application.Exit(); //đóng giao diện } } //catch catch (Exception e) { DialogResult dlr = MessageBox.Show("Có lỗi, bạn có muốn tiếp tục. \n" + e, "Thông báo", MessageBoxButtons.YesNo); if (dlr == DialogResult.Yes) { // lưu ảnh chụp màn hình cuối cùng(đoạn này copy hoàn toàn trên Google) screenBitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); screenGraphics = Graphics.FromImage(screenBitmap); screenGraphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); screenBitmap.Save(saveDialog.FileName, ImageFormat.Png); //đóng hoàn toàn ứng dụng firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở frmKTChucNang fr1 = new frmKTChucNang(); fr1.Show(); } else { firefoxDriver.Quit(); //đóng cửa sổ trình duyệt vừa mở Application.Exit(); //đóng giao diện } } // this.Show(); } }//hàm đi đến các công cụ chính trong trang online
public void addConsentToPatient() { IWebDriver driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(link); Thread.Sleep(3000); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).SendKeys("root"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).SendKeys("password"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[5]/div[1]/app-button/button")).Click(); Thread.Sleep(5000); driver.FindElement(By.XPath("//div[contains(@class,'organization-container')]/div[2]")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class, 'nav-items flex-main-start')]/div[2]")).Click(); Thread.Sleep(5000); driver.FindElement(By.XPath("//div[contains(@class,'body-container flex')]/app-tr[1]/div/div/div/app-tc[4]/div")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class,'actions-wrapper tiny')]/div[2]/div[2]")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("//div[contains(@class,'main-container clickable')]")).Click(); Thread.Sleep(1000); IList <IWebElement> consentlist = driver.FindElements(By.XPath("//app-dropdown/div/div/div")); int consent_count = consentlist.Count(); System.Diagnostics.Debug.WriteLine("Consents: " + consent_count); Thread.Sleep(2000); for (int j = 1; j <= consent_count; j++) { driver.FindElement(By.XPath("//app-dropdown/div/div[contains(@class,'dropdown-container sublabel')]/div[" + j + "]")).Click(); Thread.Sleep(1000); driver.FindElement(By.XPath("//button[contains(@class,'label btnPrimary')]")).Click(); Thread.Sleep(2000); try { driver.FindElement(By.XPath("//div[contains(text(),'Consent already added to the patient.')]")); Thread.Sleep(2000); } catch (NoSuchElementException) { driver.FindElement(By.XPath("//div[contains(@class,'left-content flex-cross-center clickable faded')]")).Click(); break; } finally { driver.FindElement(By.XPath("//div[contains(@class,'main-container clickable')]")).Click(); Thread.Sleep(3000); } } driver.Close(); driver.Quit(); }
public void checkConsentDef() { IWebDriver driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(link); Thread.Sleep(3000); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[1]/app-input/div/input")).SendKeys("root"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).Click(); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[4]/form/div[2]/app-input/div/input")).SendKeys("password"); driver.FindElement(By.XPath("/html/body/app-root/div/app-login/div/div/div/div[5]/div[1]/app-button/button")).Click(); Thread.Sleep(5000); driver.FindElement(By.XPath("//div[contains(@class,'organization-container')]/div[2]")).Click(); Thread.Sleep(2000); IList <IWebElement> consentlist = driver.FindElements(By.XPath("//div[contains(@class,'inner-wrapper flex-cross-center')]")); int consent_count = consentlist.Count(); consent_count -= 1; System.Diagnostics.Debug.WriteLine("Consents: " + consent_count); if (consent_count == 0) { driver.Close(); driver.Quit(); } else if (consent_count == 1) { System.Diagnostics.Debug.WriteLine("Consents: " + consent_count); driver.Close(); driver.Quit(); } else { int wholeNum = consent_count / 10; try { for (int k = 1; k <= 10; k++) { driver.FindElement(By.XPath("//div[contains(@class,'body-container flex')]/app-tr[" + k + "]/div/div/div/app-tc[3]/div")).Click(); Thread.Sleep(3000); driver.FindElement(By.XPath("//div[contains(@class,'left-content flex-cross-center clickable faded')]/div")).Click(); Thread.Sleep(3000); } } catch (NoSuchElementException) { } try { driver.FindElement(By.XPath("//div[contains(@class,'pagination-container flex-main-end ng-star-inserted')]")); Thread.Sleep(2000); for (int j = 1; j <= wholeNum; j++) { driver.FindElement(By.XPath("//ul[contains(@class,'ngx-pagination ng-star-inserted')]/li[contains(@class,'pagination-next ng-star-inserted')]")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2); } } catch (NoSuchElementException) { } driver.Close(); driver.Quit(); } }
public void ShouldAllowUserToSuccessfullyOverrideTheHomePage() { FirefoxProfile profile = new FirefoxProfile(); profile.SetPreference("browser.startup.page", "1"); profile.SetPreference("browser.startup.homepage", javascriptPage); IWebDriver driver2 = new FirefoxDriver(profile); try { Assert.AreEqual(javascriptPage, driver2.Url); } finally { driver2.Quit(); } }
static void Main(string[] args) { IWebDriver driver = new FirefoxDriver(); driver.Url = "http://www.google.com"; }
public void ShouldBeAbleToStartMoreThanOneInstanceOfTheFirefoxDriverSimultaneously() { IWebDriver secondDriver = new FirefoxDriver(); driver.Url = xhtmlTestPage; secondDriver.Url = formsPage; Assert.AreEqual("XHTML Test Page", driver.Title); Assert.AreEqual("We Leave From Here", secondDriver.Title); // We only need to quit the second driver if the test passes secondDriver.Quit(); }
public void IntiailizeDriver(ref IWebDriver driver, ref bool isBrowserDimendion, ref List <IWebDriver> driverlist, ref int width, ref int height, ref string addonsPath) { if ((FirefoxProfilePath.Length != 0) && Directory.Exists(FirefoxProfilePath) && (FirefoxProfilePath.Split('.').Last().ToString().ToLower() != "zip")) { string ffProfileSourcePath = FirefoxProfilePath; DirectoryInfo ffProfileSourceDir = new DirectoryInfo(ffProfileSourcePath); if (!ffProfileSourceDir.Exists) { throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0012")); } FfProfile = new FirefoxProfile(ffProfileSourceDir.ToString()); if ((Common.Utility.GetParameter("FirefoxProfilePath")).Equals(Common.Utility.GetVariable("FirefoxProfilePath"))) { InitFireFox(ref driver, ref isBrowserDimendion, ref driverlist, ref width, ref height); Common.Utility.SetVariable("FirefoxProfilePath", _ffProfileDestDir.ToString()); } else { //If Profile path is empty in parameter file then add setpreference to profile.: if (Common.Utility.GetParameter("FirefoxProfilePath").Equals("")) { FfProfile.SetPreference("webdriver_assume_untrusted_issuer", false); } InitFireFox(ref driver, ref isBrowserDimendion, ref driverlist, ref width, ref height); } } else { // If "addonsPath" contains path then load addons from that directory path. if (addonsPath.Length != 0) { try { string adPath = addonsPath; if (!Directory.Exists(adPath)) { throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0014")); } DirectoryInfo adDir = new DirectoryInfo(adPath); DirectoryInfo adDirTemp = new DirectoryInfo("AddonsTemp"); adDirTemp.Create(); foreach (FileInfo fi in adDir.GetFiles()) { fi.CopyTo(Path.Combine(adDirTemp.FullName, fi.Name), true); } int firebugCount = 0; string[] addonFilePaths = Directory.GetFiles(adPath); FfProfile = new FirefoxProfile(); FfProfile.SetPreference("webdriver_assume_untrusted_issuer", false); FfProfile.SetPreference("network.cookie.lifetimePolicy", 0); FfProfile.SetPreference("privacy.sanitize.sanitizeOnShutdown", false); FfProfile.SetPreference("privacy.sanitize.promptOnSanitize", false); SetCommonPreferences(); //Assigning profile location so that firefox can next time use same profile to open Common.Utility.SetVariable("FirefoxProfilePath", FfProfile.ProfileDirectory.ToString()); // Add all the addons found in the specified addon directory foreach (FileInfo afi in adDirTemp.GetFiles()) { if (afi.Name.ToLower().Contains("firebug")) { firebugCount++; } FfProfile.AddExtension(adDirTemp.Name + '/' + afi.Name); } // If user placed multiple versions of firebug in Addons directory then give error if (firebugCount > 1) { throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0015")); } // Start firefox with the profile that contains all the addons in addon directory // driver = new FirefoxDriver(FfProfile); driver = new FirefoxDriver(); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(150); driver.Manage().Window.Maximize(); if (isBrowserDimendion) { driver.Manage().Window.Size = new System.Drawing.Size(width, height); } driverlist.Add(driver); } catch (Exception e) { throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0009").Replace("{MSG}", e.Message)); } } else { FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(Property.ApplicationPath + @"\Exes", "geckodriver.exe"); driver = new FirefoxDriver(service); driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(150); driver.Manage().Window.Maximize(); if (isBrowserDimendion) { driver.Manage().Window.Size = new System.Drawing.Size(width, height); } driverlist.Add(driver); } //Add WebDriver Profile File to list of files that need to be deleted in temp folder. // Common.Property.ListOfFilesInTempFolder.Add(Common.Utility.GetVariable("FirefoxProfilePath")); } }
/// <summary> /// Login to Openbet admin /// </summary> /// Authour: pradeep /// Created Date: 02-Feb-2012 public ISelenium LogOnToAdmin() { IWebDriver ffDriver = new FirefoxDriver(); ISelenium myBrowser = new WebDriverBackedSelenium(ffDriver, FrameGlobals.AdminBase); myBrowser.Start(); myBrowser.Open(FrameGlobals.AdminBase); ffDriver.Manage().Window.Maximize(); myBrowser.WaitForPageToLoad(FrameGlobals.PageLoadTimeOut); // PreProd has some issues myBrowser.Refresh(); myBrowser.WaitForPageToLoad(FrameGlobals.PageLoadTimeOut); myBrowser.Type(AdminSuite.CommonControls.AdminHomePage.UsrNmeTxtBx, FrameGlobals.AdminUserName); myBrowser.Type(AdminSuite.CommonControls.AdminHomePage.PwdTxtBx, FrameGlobals.AdminPassWord); myBrowser.WaitForPageToLoad(FrameGlobals.PageLoadTimeOut); myBrowser.Click(AdminSuite.CommonControls.AdminHomePage.LoginBtn); myBrowser.WaitForPageToLoad(FrameGlobals.PageLoadTimeOut); Thread.Sleep(2000); return myBrowser; }
private static FirefoxDriver GetFirefoxDriver() { FirefoxDriver driver = new FirefoxDriver(GetFirefoxOptions()); return(driver); }
public void SetupTest() { driver = new FirefoxDriver(); }
public static IWebDriver OpenFireFoxDriver(string URL) { var driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(URL); return driver; }