示例#1
0
        public void CleanUp()
        {
            OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(PropertiesCollection.driver, TimeSpan.FromSeconds(5));
            PropertiesCollection.driver.Close();

            Console.WriteLine("Close the browser");
        }
示例#2
0
 public HomePageBBC(IWebDriver driver)
 {
     _driver = driver;
     PageFactory.InitElements(_driver, this);
     _wait = new WebDriverWait(_driver, new TimeSpan(0, 0, 5));
     WaitUntilPageLoaded();
 }
示例#3
0
        public void clickWhenReady(By locator, int timeout)
        {
            WebDriverWait wait    = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
            WebElement    element = wait.Until(ExpectedConditions.ElementToBeClickable(locator));

            element.Click();
        }
示例#4
0
        internal IWebElement waitForElementIsPresent(By lookupBy, int maxWaitTime = 60)
        {
            IWebElement element = null;

            try
            {
                element = new WebDriverWait(driver, TimeSpan.FromSeconds(maxWaitTime)).Until(ExpectedConditions.ElementExists(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);
        }
        public static void GoTo()
        {
            Driver.Instance.Navigate().GoToUrl(Driver.BaseAddress + "wp-login.php");
            var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10));

            wait.Until(d => d.SwitchTo().ActiveElement().GetAttribute("id") == "user_login");
        }
示例#6
0
        public void ClickWithoutUsingExpectedConditions(By by)
        {
            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));

            IWebElement element = wait.Until <IWebElement>(condition => {
                try
                {
                    IWebElement tempElement = _driver.FindElement(by);
                    return(tempElement.Enabled ? tempElement : null);
                }
                catch
                {
                    return(null);
                }
            });

            try
            {
                element.Click();
            }
            catch (NullReferenceException)
            {
                Assert.Fail($"Exception occurred in SeleniumHelper.Click(): element located by {by.ToString()} could not be located within 10 seconds.");
            }
        }
        public async Task GoToPage(string url)
        {
            _driver.Navigate().GoToUrl(url);
            var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(_driver, TimeSpan.FromSeconds(90.00));

            wait.Until(driver => ((IJavaScriptExecutor)_driver).ExecuteScript("return document.readyState").Equals("complete"));
            await Task.CompletedTask;
        }
        public static void WaitForElementDisappear(string xpath, int seconds)
        {
            var elm = FindElement(xpath);

            Console.WriteLine("element displayed: " + elm.Displayed);
            object o = new OpenQA.Selenium.Support.UI.WebDriverWait(driver,
                                                                    TimeSpan.FromSeconds(seconds)).Until(ExpectedConditions.InvisibilityOfElementLocated(By.XPath(xpath)));
        }
示例#9
0
        public News GetLasNewsFromSite(string link)
        {
            StartBrowser();
            OpenQA.Selenium.Support.UI.WebDriverWait wait =
                new OpenQA.Selenium.Support.UI.WebDriverWait(driver, System.TimeSpan.FromSeconds(120));

            wait.Until(webDriver => ((OpenQA.Selenium.IJavaScriptExecutor)webDriver)
                       .ExecuteScript("return document.readyState").Equals("complete"));
            driver.Navigate().GoToUrl(link);

            System.Threading.Thread.Sleep(5000);
            string newsHeader = driver.FindElement(OpenQA.Selenium.By
                                                   .ClassName("article__header"))
                                .FindElement(OpenQA.Selenium.By
                                             .ClassName("article__title")).Text;

            string imgLink = driver.FindElement(
                OpenQA.Selenium.By
                .ClassName("photoview__open"))
                             .FindElement(OpenQA.Selenium.By
                                          .TagName("img"))
                             .GetAttribute("src");

            var texts = driver.FindElements(OpenQA.Selenium.By
                                            .ClassName("article__text"));

            OpenQA.Selenium.IJavaScriptExecutor js =
                (OpenQA.Selenium.IJavaScriptExecutor)driver;

            var sb = new System.Text.StringBuilder();

            string shortText = texts[0].Text;

            foreach (var text in texts)
            {
                if (text != null)
                {
                    sb.Append(text.Text);
                }
                else
                {
                    sb.Append("");
                }
            }


            News news = new News()
            {
                Date       = System.DateTime.Now.ToString("yyyy-dd-dd hh:ss:ff"),
                ShortStory = Translation.Translate("en", shortText),
                FullStory  = Translation.Translate("en", sb.ToString()),
                Link       = link,
                Header     = Translation.Translate("en", newsHeader),
                ImageLink  = imgLink
            };

            return(news);
        }
示例#10
0
        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)));
            }
        }
 public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
 {
     if (timeoutInSeconds > 0)
     {
         var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
         return(wait.Until(drv => drv.FindElement(by)));
     }
     return(driver.FindElement(by));
 }
        //Menu XPath is the XPath of menu for which you have to perform a hover operation

        public void MouseHover(String ReportButton)
        {
            OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(10));
            var     element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(ReportButton)));
            Actions action  = new Actions(driver);

            action.MoveToElement(element).Perform();
            //Waiting for the menu to be displayed
            System.Threading.Thread.Sleep(4000);
        }
示例#13
0
        public OpenQA.Selenium.Support.UI.WebDriverWait WaitForElement(int seconds)
        {
            TimeSpan span = TimeSpan.FromSeconds(seconds);

            OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(WebDriver, span);

            //IWebElement foundElement = wait.Until(web => WebDriver.FindElement(By.XPath(xPath)));
            //return foundElement;
            return(wait);
        }
示例#14
0
        protected IWebElement WaitForElementByTime(By locator, int seconds)
        {
            WaitUntilPageReady();
            OpenQA.Selenium.Support.UI.WebDriverWait waitTime = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(seconds));
            waitTime.Until(ExpectedConditions.ElementExists(locator));
            IWebElement element = driver.FindElement(locator);

            waitTime.Until(ExpectedConditions.ElementToBeClickable(element));
            return(element);
        }
示例#15
0
        public void TestMethod1()
        {
            using (IWebDriver webDriver = CreateWebDriver())
            {
                // googleに遷移
                webDriver.Navigate().GoToUrl(@"https://www.google.co.jp");
                // CSSセレクタを使って要素を取得
                IWebElement element = webDriver.FindElement(By.CssSelector("input[name=\"q\"]"));
                // 取得した要素にテキストを入力してsubmit
                const string SearchWord = "selenium";
                element.SendKeys(SearchWord);
                element.Submit();

                /*
                 * //submitの直後ではURLもタイトルも変わっていない(=遷移が終わっていない(Seleniumの仕様?Edgeの仕様?Googleの仕様?))
                 * Console.WriteLine(webDriver.Url);
                 * Console.WriteLine(webDriver.Title);
                 */

                //sleepしてからチェックすると遷移してるから、Submitが終わった後、ブラウザ側の処理が終わるまで待機する必要がある
                //Thread.Sleep(3000);
                //遷移が終わるまで最大3秒待機する
                const string expectedTitle = "selenium - Google 検索";
                //const string expectedTitle = "テストケース誤り";
                OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(webDriver, TimeSpan.FromSeconds(3));
                var transfered = wait.Until(e => e.Title == expectedTitle);

                /*
                 * Console.WriteLine(webDriver.Url);
                 * Console.WriteLine(webDriver.Title);
                 */

                var screenShot = ((ITakesScreenshot)webDriver).GetScreenshot();
                // TODO:ヘルパーに切り出したほうがよさそう
                const string ScreenshotDirectoryRoot = "SeleniumSample";
                string       screenShotDirectoryPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop), ScreenshotDirectoryRoot, DateTime.Now.ToString("yyyyMMddHHmm"));
                if (!System.IO.Directory.Exists(screenShotDirectoryPath))
                {
                    System.IO.Directory.CreateDirectory(screenShotDirectoryPath);
                }
                string screenShotName     = $"{this.GetType().Name}.{nameof(TestMethod1)}.01.png";
                string screenShotFullName = System.IO.Path.Combine(screenShotDirectoryPath, screenShotName);
                screenShot.SaveAsFile(screenShotFullName, ScreenshotImageFormat.Png);

                // 最初のリンクの文字列に検索語句が含まれていることを確認する
                var    firstElement = webDriver.FindElement(By.ClassName("LC20lb")); //2020/05/29時点。
                string actualText   = firstElement.Text;
                Console.WriteLine(actualText);
                Assert.IsTrue(actualText.ToLower().Contains(SearchWord), $"actual text:{actualText}");
                //Assert.IsTrue(actualText.ToLower().Contains("テストケース誤り"), $"actual text:{actualText}");

                // ブラウザ終了
                webDriver.Quit();
            }
        }
示例#16
0
 private static void WaitForLoad(IWebDriver driver)
 {
     try
     {
         var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
         wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
     }
     catch (Exception)
     {
     }
 }
示例#17
0
        public override void MakeSortedDesc()
        {
            WebDriverWait wait = new WebDriverWait(GetDriver(), TimeSpan.FromSeconds(5));

            wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
            wait.Until(d => Page.SortingDropdown.Displayed);
            Page.SortingDropdown.Click();
            wait.Until(d => Page.ExpensiveFilter.Displayed);
            Page.ExpensiveFilter.Click();
            wait.Until(d => Page.AppliedSortingLabel.Displayed);
        }
        public static void OpenChromeBrowser()
        {
            var service = ChromeDriverService.CreateDefaultService(@"C:\Users\janani_jeeva", "chromedriver.exe");

            ChromeOptions chromeOptions = new ChromeOptions();

            driver = new ChromeDriver(service, chromeOptions);
            wait   = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30));
            ChooseSettings("QA");
            driver.Manage().Window.Maximize();
        }
示例#19
0
        public AppiumHelper(ConfigurationHelper configuration)
        {
            var driverOption = new AppiumOptions();

            driverOption.AddAdditionalCapability(MobileCapabilityType.PlatformName, configuration.PlatformName);
            driverOption.AddAdditionalCapability(MobileCapabilityType.DeviceName, configuration.DeviceName);
            driverOption.AddAdditionalCapability(MobileCapabilityType.App, configuration.app);
            driverOption.AddAdditionalCapability("avd", configuration.avd);

            Driver = new AndroidDriver <AndroidElement>(new Uri(configuration.AppiumServer), driverOption);

            Wait = new OpenQA.Selenium.Support.UI.WebDriverWait(Driver, TimeSpan.FromSeconds(30));
        }
示例#20
0
        public void TC01_FPWeb_ValidateMenu()
        {
            test = extent.CreateTest("TC01_FPWeb_Validation");

            var dr = Lib_Login.Login();

            var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(dr, new TimeSpan(0, 0, 30));

            var SidebarMenu = new clsMainPage_SidebarMenu();

            PageFactory.InitElements(dr, SidebarMenu);



            SidebarMenu.Summary_link.Click();

            test.Pass("Assertion Passed");



            //      SidebarMenu.Calendar_link.Click();

            //        var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("href12005")));

            //         SidebarMenu.ControlHoursReport_link.Click();

            //  SidebarMenu.CurrencyHistoryReport_link.Click();



            //SidebarMenu.EventsReport_link.Click();

            //  SidebarMenu.Roster_link.Click();

            //  SidebarMenu.DailyScheduling_link.Click();

            //  SidebarMenu.DutyTimes_link.Click();

            //  SidebarMenu.ProgrammeViewer_link.Click();

            //   SidebarMenu.KnowledgeBase_link.Click();

            //          SidebarMenu.StatusBoard_link.Click();

            //    SidebarMenu.StudentResults_link.Click();


            //  Lib_Logout.Logout(dr);
        }
示例#21
0
 public WebElement WaitUntilElementExists(By lookupBy, int timeout = 10)
 {
     try
     {
         var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
         return(wait.Until(ExpectedConditions.ElementExists(lookupBy)));
     }
     catch (NoSuchElementException ex)
     {
         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);
         // Assert.Fail(lookupBy + " is not visible for " + timeout + " seconds." + " with message :" + ex.Message);
         throw new Exception(lookupBy + " is not visible for " + timeout + " seconds." + " with message :" + ex.Message);
     }
 }
示例#22
0
        public IWebElement FindElement(By by, int timeoutInSeconds = -1)
        {
            if (timeoutInSeconds > 0)
            {
                var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
                return(wait.Until(drv =>
                {
                    var _els = drv.FindElements(by);
                    return _els.Count > 0 ? _els[0] : null;
                }));
            }
            var els = driver.FindElements(by);

            return(els.Count > 0 ? els[0] : null);
        }
示例#23
0
        public override void ApplyFilter(string filterName)
        {
            By            byFilter = ByFilter(filterName);
            WebDriverWait wait     = new WebDriverWait(GetDriver(), TimeSpan.FromSeconds(5));

            wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
            IWebElement productFilter = wait.Until(ExpectedConditions.ElementToBeClickable(byFilter));

            //Actions a = new Actions(driver);
            //a.Click(driver.FindElement(by)).Build().Perform();
            GetDriver().FindElement(byFilter).Click();
            By byFilterApplied = ByAppliedFilter(filterName);

            wait.Until(ExpectedConditions.ElementIsVisible(byFilterApplied));
        }
        public bool CheckElementIsVisible(By by)
        {
            WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(Constants.DEFAULT_TIMEOUT));

            return(wait.Until(driver => {
                try
                {
                    IWebElement tempElement = _driver.FindElement(by);
                    return tempElement.Displayed;
                }
                catch
                {
                    return false;
                }
            }));
        }
示例#25
0
        private void SendKeysByXpath(string xpath, string sendKeys)
        {
            var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromMinutes(2));

            try
            {
                var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath(xpath)));
                element.SendKeys(sendKeys);
            }
            catch
            {
                Thread.Sleep(5000);
                var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.XPath(xpath)));
                element.SendKeys(sendKeys);
            }
        }
示例#26
0
        public bool waitForInVisibilityOfElement(By by, string locator)
        {
            bool          flag = false;
            TimeSpan      time = new TimeSpan(30);
            WebDriverWait wait = new WebDriverWait(driver, time);

            try
            {
                wait.Until(ExpectedConditions.InvisibilityOfElementLocated(by));
                flag = true;
                return(flag);
            }
            catch (Exception)
            {
                return(flag);
            }
        }
      public void AddPerson()
      {
         driver.Manage().Window.Maximize();
         driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));

         driver.Navigate().GoToUrl(this.baseURL);
         driver.FindElementByLinkText("People").Click();
         driver.FindElementByLinkText("Create New").Click();
         driver.FindElementById("FirstName").Clear();
         driver.FindElementById("FirstName").SendKeys(browser);
         driver.FindElementById("LastName").Clear();
         driver.FindElementById("LastName").SendKeys("User");
         driver.FindElementByCssSelector("input.btn").Click();

         // Force chrome to slow down so the click is registered
         var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30));
         wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
      }
示例#28
0
        public void FirstSeleniumTest()
        {
            var driver = new OpenQA.Selenium.Firefox.FirefoxDriver();

            //var driver = new OpenQA.Selenium.Chrome.ChromeDriver();
            driver.Navigate().GoToUrl("http://www.google.pl");
            Assert.That(driver.Title, Is.EqualTo("Google"));
            var element = driver.FindElementById("gbqfq");

            element.SendKeys("google\n");
            var wait   = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(10));
            var result = wait.Until(d => {
                return(d.PageSource.Contains("Wyszukiwarka stron WWW"));
            });

            Assert.IsTrue(result);
            driver.Quit();
        }
示例#29
0
        public void VerifyAllProductNamesContain(params string[] queries)
        {
            WebDriverWait wait = new WebDriverWait(GetDriver(), TimeSpan.FromSeconds(3));

            wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
            wait.Until(d => page.Products.All(elt => elt.Displayed));
            //wait.Until(d => page.ProductsContainer.Displayed);
            Assert.IsTrue(page.Products.Count > 0, "Products count is {0}", page.Products.Count);
            foreach (IWebElement product in page.Products)
            {
                bool foundOnceOrMore = false;
                foreach (string q in queries)
                {
                    bool found = product.Text.ToLower().Contains(q.ToLower());
                    foundOnceOrMore = foundOnceOrMore || found;
                }
                Assert.IsTrue(foundOnceOrMore, "Product name {0} is not suitable", product.Text);
            }
        }
        public static void CaptureScreenshot()
        {
            var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(m_Driver, TimeSpan.FromSeconds(10));
            // wait.Until(driver.FindElement(By.Id("knownElementId")).Displayed);

            string           scrshotpath      = ConfigurationManager.AppSettings["screenshotpath"];
            ITakesScreenshot screenshotDriver = m_Driver as ITakesScreenshot;

            try
            {
                Screenshot screenshot = screenshotDriver.GetScreenshot();
                string     timestamp  = DateTime.Now.ToString("yyyy-MM-dd-hhmm-ss");
                screenshot.SaveAsFile(scrshotpath + "iRePORT_" + timestamp + ".png");
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#31
0
        public void InitTests()
        {
            homeURL = "http://localhost:3000/";
            var options = new ChromeOptions();

            options.AddExcludedArgument("enable-automation");
            options.AddAdditionalCapability("useAutomationExtension", false);
            options.AddArgument("--start-maximized");
            options.AddArgument("--ignore-certificate-errors");
            options.AddArgument("--disable-popup-blocking");
            options.AddArgument("--incognito");

            driver = new ChromeDriver(options)
            {
                Url = homeURL
            };

            wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(10));
        }