public bool click(By locator, string locatorName) { bool flag = true; try { /*Highlight element*/ WebElement webElement = driver.FindElement(locator); JavascriptExecutor js = driver as JavascriptExecutor; js.ExecuteScript("arguments[0].style.border='2px solid yellow'", webElement); js.ExecuteScript("arguments[0].click();", webElement); /*Highlight code ends*/ //Thread.Sleep(500); // driver.FindElement(locator).Click(); //js.ExecuteScript("arguments[0].click();", webElement); //flag = true; ExtentReport.ReportPass("The Element <b>" + locatorName + "</b> Click Successfull"); } catch (Exception ex) { //TakeScreenShot(); ExtentReport.ReportPass("The Element <b>" + locatorName + "</b> Click Failed :" + ex.Message); return(flag); } return(flag); }
public bool isElementDisplayed(WebElement element) { bool flag = false; try { for (int i = 0; i < 5; i++) { if (element.Displayed) { flag = true; break; } else { Thread.Sleep(5); } } } catch (Exception ex) { flag = false; TakeScreenShot(); // throw new Exception(ex.Message); } return(flag); }
public bool selectByOptionText(By locator, string value, string locatorName) { bool flag = false; try { WebElement ListBox = driver.FindElement(locator); ReadOnlyCollection <WebElement> options = ListBox.FindElements(By.TagName("option")); foreach (var option in options) { string opt = option.Text.Trim(); if (opt.ToLower().Equals(value.ToLower().Trim())) { option.Click(); flag = true; break; } } } catch (Exception e) { TakeScreenShot(); throw new Exception("Option with value attribute " + value + " is Not Select from the DropDown " + locatorName + " " + e.Message); } return(flag); }
public bool waitForVisibilityOfElementUntillTimeout(By lookupBy, double timeout) { bool bln = false; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)); try { WebElement ele = wait.Until(ExpectedConditions.ElementIsVisible(lookupBy));//sunil bln = true; } catch (Exception ex) { try { TakeScreenShot(); Assert.Fail(lookupBy + " is not visible for " + timeout + " seconds." + " with message :" + ex.Message); throw new Exception(ex.Message); } catch (Exception ex1) { Assert.Fail("Failed to take screenshot: " + ex1.ToString()); } } return(bln); }
static void Login(string userEmail, string password) { //var sleepTime1 = 25; var enterKey = "\r\n"; var tabKey = "\t"; var kbd = driver.Keyboard; kbd.SendKeys(userEmail); //System.Threading.Thread.Sleep(sleepTime1); OpenQA.Selenium.IWebElement LoginBox = driver.FindElementByName("loginemailaddress"); var inputValueAtrib = LoginBox.GetAttribute("value"); // driver.ExecuteScript("document.getElementsByTagName('loginemailaddress').setAttribute('value', '*****@*****.**')"); ///html/body/form/table/tbody/tr/td[2]/main/blockquote/table/tbody/tr/td[1]/p[3]/input //var obj = driver.ExecuteScript("document.getElementsByName('loginemailaddress')"); var obj = driver.ExecuteScript("document.getElementsByName('loginemailaddress')"); //System.Threading.Thread.Sleep(sleepTime1); kbd.SendKeys(tabKey); //System.Threading.Thread.Sleep(sleepTime1); kbd.SendKeys(password); //System.Threading.Thread.Sleep(sleepTime1); kbd.SendKeys(tabKey); //System.Threading.Thread.Sleep(sleepTime1); kbd.SendKeys(enterKey); // System.Threading.Thread.Sleep(sleepTime1); }
internal WebElement waitForElementVisible(By lookupBy, int maxWaitTime = 60) { WebElement element = null; try { element = new WebDriverWait(driver, TimeSpan.FromSeconds(maxWaitTime)).Until(ExpectedConditions.ElementIsVisible(lookupBy)); } catch (Exception ex) { throw new Exception(ex.Message); } if (element != null) { try { string script = String.Format(@"arguments[0].style.cssText = ""border-width: 4px; border-style: solid; border-color: {0}"";", "orange"); JavascriptExecutor jsExecutor = (JavascriptExecutor)driver; //jsExecutor.ExecuteScript(script, new object[] { element }); //jsExecutor.ExecuteScript(String.Format(@"$(arguments[0].scrollIntoView(true));"), new object[] { element }); } catch { } } return(element); }
/// <summary> /// Auto Login to HTO /// </summary> /// <param name="userEmail">User account</param> /// <param name="password">Account Password</param> /// <param name="loginURL">HTO Login page</param> public static void Login(string userEmail, string password, string loginURL) { // used for sending clicks and and characters Actions actions = new Actions(driver); // set driver timeout and launch browser Console.WriteLine("Goto " + loginURL); driver.Manage().Timeouts().ImplicitWait = new TimeSpan(0, 0, 12); driver.Navigate().GoToUrl(loginURL); IWebElement body = driver.FindElement(By.TagName("body")); body.SendKeys(OpenQA.Selenium.Keys.Control + 'T'); // Get the elements of the login elements from HTML OpenQA.Selenium.IWebElement LoginBox = driver.FindElementByName("loginemailaddress"); OpenQA.Selenium.IWebElement LoginPassword = driver.FindElementByName("loginpassword"); OpenQA.Selenium.IWebElement LoginButton = driver.FindElementByName(HTOMenuButtons.Login); //Execute auto login { Console.WriteLine("logging onto HTO as " + userEmail); actions.SendKeys(LoginBox, userEmail); actions.SendKeys(LoginPassword, password); actions.Click(LoginButton); actions.Perform(); } }
public bool click(By locator, string locatorName) { bool flag = true; try { /*Highlight element*/ WebElement webElement = driver.FindElement(locator); JavascriptExecutor js = driver as JavascriptExecutor; js.ExecuteScript("arguments[0].style.border='2px solid yellow'", webElement); js.ExecuteScript("arguments[0].click();", webElement); /*Highlight code ends*/ //Thread.Sleep(500); // driver.FindElement(locator).Click(); //js.ExecuteScript("arguments[0].click();", webElement); //flag = true; } catch (Exception) { System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg; ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(Path.Combine(projectLoc, TestContext.CurrentContext.Test.Name + "-" + DateTime.Now.ToString("dd-M-yyyy", CultureInfo.InvariantCulture) + "." + format), ScreenshotImageFormat.Jpeg); return(flag); } return(flag); }
public bool selectByOptionText(By locator, string value, string locatorName) { bool flag = false; try { WebElement ListBox = driver.FindElement(locator); IReadOnlyCollection <WebElement> options = ListBox.FindElements(By.TagName("option")); foreach (var option in options) { string opt = option.Text.Trim(); if (opt.ToLower().Equals(value.ToLower().Trim())) { option.Click(); flag = true; break; } } } catch (Exception e) { System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg; ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(Path.Combine(projectLoc, TestContext.CurrentContext.Test.Name + "-" + DateTime.Now.ToString("dd-M-yyyy", CultureInfo.InvariantCulture) + "." + format), ScreenshotImageFormat.Jpeg); throw new Exception("Option with value attribute " + value + " is Not Select from the DropDown " + locatorName + " " + e.Message); } return(flag); }
public bool isElementDisplayed(WebElement element) { bool flag = false; try { for (int i = 0; i < 5; i++) { if (element.Displayed) { flag = true; break; } else { Thread.Sleep(5); } } } catch (Exception ex) { flag = false; System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg; ((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(Path.Combine(projectLoc, TestContext.CurrentContext.Test.Name + "-" + DateTime.Now.ToString("dd-M-yyyy", CultureInfo.InvariantCulture) + "." + format), ScreenshotImageFormat.Jpeg); // throw new Exception(ex.Message); } return(flag); }
public void clickWhenReady(By locator, int timeout) { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)); WebElement element = wait.Until(ExpectedConditions.ElementToBeClickable(locator)); element.Click(); }
public bool waitForVisibilityOfElement(By lookupBy, double timeout) { bool flag = false; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)); try { WebElement ele = wait.Until(ExpectedConditions.ElementIsVisible(lookupBy)); flag = true; ExtentReport.ReportPass("The element is visible before <b>" + timeout + "</b> seconds"); } catch (Exception ex) { try { //TakeScreenShot(); ExtentReport.ReportFail("The element is not visible :<b>" + ex.Message + "</b>"); //Assert.Fail(lookupBy + " is not visible for " + timeout + " seconds." + " with message :" + ex.Message); flag = false; } catch (Exception ex1) { //Assert.Fail("Failed to take screenshot: " + ex1.ToString()); } } return(flag); }
public static void RightClick(this IWebElement element) { var remote = (RemoteWebElement)element; var action = new Actions(remote.WrappedDriver); action.ContextClick(element).Build().Perform(); }
public static bool Assert(UI.UIAssertAction action, OpenQA.Selenium.IWebDriver webDriver) { By locator = SeleniumUIHelper.GetBy(action.Element); OpenQA.Selenium.IWebElement element = SeleniumUIHelper.GetElement(webDriver, locator); switch (action.AssertType) { case UIActionSeertType.Text: return(CheckTextAssert(element, action)); case UIActionSeertType.CssClass: return(CheckCssClassAssert(element, action)); case UIActionSeertType.Count: System.Collections.ObjectModel.ReadOnlyCollection <IWebElement> elements = SeleniumUIHelper.GetElements(webDriver, locator); return(CheckCountElementAssert(elements, action)); case UIActionSeertType.Browser: return(CheckBrowserAssert(webDriver, action)); case UIActionSeertType.Exist: default: return(CheckExistAssert(element, action)); } }
protected QA.IWebElement FindElementByXPathName(string xpath) { QA.IWebElement theElement = null; _WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3)); theElement = _WebDriver.FindElement(QA.By.XPath(xpath)); return(theElement); }
public void GetGitGubSettingsTest() { //Arrange bool serviceLoaded; //Act string serviceUrl = _serviceUrl + "/api/Settings/GetGitHubSettings"; Console.WriteLine("serviceUrl:" + serviceUrl); _driver.Navigate().GoToUrl(serviceUrl); serviceLoaded = (_driver.Url == serviceUrl); OpenQA.Selenium.IWebElement data = _driver.FindElement(By.XPath(@"/html/body/pre")); Console.WriteLine("data:" + data.Text); List <GitHubSettings> settings = new(); if (string.IsNullOrEmpty(data?.Text) == false) { settings = JsonConvert.DeserializeObject <List <GitHubSettings> >(data.Text); } //Assert Assert.IsTrue(serviceLoaded); Assert.IsTrue(data != null); Assert.IsTrue(settings.Count >= 0); Assert.IsTrue(settings[0].Owner != null); }
private async void btn_Login_Selenium_Click(object sender, RoutedEventArgs e) { var userName = this.tbox_UserName_Selenium.Text.Trim(); var password = this.tbox_Password_Selenium.Text.Trim(); if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { EMessageBox.Show("请输入用户名或密码"); return; } using (OpenQA.Selenium.IWebDriver driver = new OpenQA.Selenium.Edge.EdgeDriver()) { driver.Navigate().GoToUrl("http://i.360.cn"); //driver.Url = "http://i.360.cn"是一样的 var source = driver.PageSource; this.rtbox_BeforeLoginContent_Selenium.Document = new FlowDocument(new Paragraph(new Run(source))); //这个等待是无效的,只是测试代码,可以直接启用下载获取username的代码 QA.Support.UI.WebDriverWait wait = new QA.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(2)); QA.IWebElement userNameEle = wait.Until <QA.IWebElement>(d => d.FindElement(QA.By.Name("userName"))); //QA.IWebElement userNameEle = driver.FindElement(QA.By.Name("userName")); QA.IWebElement passwordEle = driver.FindElement(QA.By.Name("password")); QA.IWebElement loginEle = driver.FindElement(QA.By.ClassName("quc-button-submit quc-button quc-button-primary")); //填写用户名 userNameEle.SendKeys(QA.Keys.Tab); userNameEle.Clear(); userNameEle.SendKeys(userName); //主动等待2秒 driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2); //填写密码 passwordEle.SendKeys(QA.Keys.Tab); passwordEle.Clear(); passwordEle.SendKeys(password); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2); //点击登录按钮 loginEle.Click(); //主动等待5秒 //使用driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);这种方式等待无效 //登录需要时间,如果直接去获取Cookie,获取的还是未登录前的Cookie System.Threading.Thread.Sleep(5000); //Cookies var cookies = driver.Manage().Cookies.AllCookies; var cookieContainer = SeleniumUtil.CookieConvert(cookies); var html = await WebUtil.GetHtmlSource("http://i.360.cn", cookieContainer : cookieContainer); this.rtbox_AfterLoginContent_Selenium.Document = new FlowDocument(new Paragraph(new Run(html.Item1))); } }
//Function to create TM public void AddTM(IWebDriver driver) { //Create a new material //Click on Create New button OpenQA.Selenium.IWebElement CreateNewButton = driver.FindElement(By.XPath("//*[@id='container']/p/a")); CreateNewButton.Click(); //Click on TypeCode driver.FindElement(By.XPath("//*[@id='TimeMaterialEditForm']/div/div[1]/label")).Click(); //Select Material from drop-down driver.FindElement(By.XPath("//*[@id='TimeMaterialEditForm']/div/div[1]/div/span[1]/span/span[1]")).Click(); //Enter the Code IWebElement Code = driver.FindElement(By.Id("Code")); Code.SendKeys("Automation"); //Enter the Description IWebElement Description = driver.FindElement(By.Id("Description")); Description.SendKeys("Coding"); //Enter the Price per unit IWebElement Price = driver.FindElement(By.XPath("//*[@id='TimeMaterialEditForm']/div/div[4]/div/span[1]/span/input[1]")); Price.SendKeys("17"); //Click on Save button IWebElement SaveButton = driver.FindElement(By.XPath("//*[@id='SaveButton']")); SaveButton.Click(); Thread.Sleep(1000); ////Verify the creation of time and material record ////Navigate to the last page //driver.FindElement(By.XPath("//*[@id='tmsGrid']/div[4]/a[4]/span")).Click(); //IWebElement actualCode = driver.FindElement(By.XPath("//*[@id='tmsGrid']/div[6]/a[4]")); //if (actualCode.Text == "Automation") //{ // Console.WriteLine("Test Passed, material created successully"); //} //else //{ // Console.WriteLine("Test Failed!"); //} //select the record to be deleted }
public static TResult?EnsureValue <TResult>(this IWebElement element, Func <IWebElement, TResult> function) { try { return(function(element)); } catch { return(default);
public QA.IWebElement FindElementByClassName(string clsName) { QA.IWebElement theElement = null; try { theElement = wd.FindElement(QA.By.ClassName(clsName)); } catch { } return(theElement); }
public static bool TryClick(this OpenQA.Selenium.IWebElement webElement, OpenQA.Selenium.IWebDriver webDriver, string url) { webElement.Click(); System.Threading.Thread.Sleep(1000); if (webDriver.Url == url) { throw new Exception("Url is not " + url); } return(true); }
public QA.IWebElement FindElementByLinkText(string text) { QA.IWebElement theElement = null; try { theElement = wd.FindElement(QA.By.LinkText(text)); } catch { } return(theElement); }
protected QA.IWebElement FindElementByLinkText(string text) { QA.IWebElement theElement = null; try { _WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3)); theElement = _WebDriver.FindElement(QA.By.LinkText(text)); } catch { } return(theElement); }
protected QA.IWebElement FindElementByClassName(string className) { QA.IWebElement theElement = null; try { _WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3)); theElement = _WebDriver.FindElement(QA.By.ClassName(className)); } catch { } return(theElement); }
public static void SetAttribute(this IWebElement element, string attribute, string value) { if (value == null) { value = ""; } value = value.Replace("'", @"\'"); var remote = (RemoteWebElement)element; remote.WrappedDriver.ExecuteJavaScript($"arguments[0].{attribute} = '{value}'", element); }
public static void SlideRangeConfirm(this IWebElement element, int valMax) { var remote = (RemoteWebElement)element; remote.WrappedDriver.ExecuteJavaScript( "$(arguments[0]).val('" + valMax + "'); " + "$(arguments[0]).scope().moving = true; " + "$(arguments[0]).scope().clicked = true; " + "$(arguments[0]).triggerHandler('change'); " + "$(arguments[0]).triggerHandler('mouseup'); ", element); }
public static void JQuerySetText(this IWebElement element, string text) { text = text.Replace(Environment.NewLine, @"\r\n"); text = text.Replace("'", @"\'"); text = JavaScriptEncoder.Default.Encode(text); var remote = (RemoteWebElement)element; remote.WrappedDriver.ExecuteJavaScript( $"$(arguments[0]).val('{text}'); " + "$(arguments[0]).trigger('change'); ", element); }
/// <summary> /// Find the element by xpath /// </summary> /// <param name="xpath"></param> /// <returns></returns> public QA.IWebElement FindElementByXPath(string xpath) { try { QA.IWebElement theElement = null; theElement = (QA.IWebElement)wd.FindElement(QA.By.XPath(xpath)); return(theElement); } catch { } return(null); }
/// <summary> /// Find the element of a specified name /// </summary> /// <param name="name"></param> /// <returns></returns> public QA.IWebElement FindElementByName(string name) { try { QA.IWebElement theElement = null; theElement = (QA.IWebElement)wd.FindElement(QA.By.Name(name)); return(theElement); } catch { } return(null); }
/// <summary> /// Find the element of a specified id /// </summary> /// <param name="id"></param> /// <returns></returns> public QA.IWebElement FindElementById(string id) { try { QA.IWebElement theElement = null; theElement = (QA.IWebElement)wd.FindElement(QA.By.Id(id)); return(theElement); } catch { } return(null); }
internal WebElement(WebDriver webDriver, OpenQA.Selenium.IWebElement webElement) { this._wd = webDriver; _webDriver = _wd.WebDriver; _webElement = webElement; }