C# 和 Selenium - 如何執行顯式等待方法?


我們可以在 C# 中使用 Selenium webdriver 執行顯式等待。這樣做是為了實現測試和頁面元素之間的同步。為了實現顯式等待,我們必須藉助 WebDriverWait 和 ExpectedCondition 類。

我們將建立一個 WebDriverWait 類的物件。webdriver 會等待指定等待時間,直到元素的預期條件滿足。

時間到期後,Selenium 會引發異常。

顯式等待本質上是動態的,這意味著如果我們設定了 5 秒的顯式等待,並且預期條件在第 3 秒滿足,那麼 webdriver 將立即進入下一步。它不會一直等到 5 秒。

一些預期條件如下:

  • UrlToBe

  • VisibilityOfAllElementsLocatedBy

  • UrlContains

  • AlertIsPresent

  • AlertState

  • ElementToBeSelected

  • ElementIsVisible

  • ElementExists

  • ElementSelectionStateToBe

  • ElementToBeClickable

  • InvisibilityOfElementWithText

  • InvisibilityOfElementLocated

  • TextToBePresentInElementLocated

  • TextToBePresentInElementValue

  • TextToBePresentInElement

  • StalenessOf

  • TitleContains

  • FrameToBeAvailableAndSwitchToIt

  • PresenceOfAllElementsLocatedBy

  • TitleIs

語法

WebDriverWait w =
new WebDriverWait(driver, TimeSpan.FromSeconds(20));
w.Until(ExpectedConditions.ElementIsVisible(By.TagName("h1")));

讓我們嘗試等待頁面上顯示文字“Team @ Tutorials Point”:

示例

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
namespace NUnitTestProject2{
   public class Tests{
      String url = "https://tutorialspoint.tw/about/about_careers.htm";
      IWebDriver driver;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         driver = new FirefoxDriver("");
      }
      [Test]
      public void Test2(){
         //URL launch
         driver.Navigate().GoToUrl(url);
         //identify element then click
         IWebElement t = driver.FindElement(By.XPath("//*[text()='Team']"));
         t.Click();
         //expected condition of Element visibility
         WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
         w.Until
         (ExpectedConditions.ElementIsVisible(By.TagName("h1")));
         //identify element then obtain text
         IWebElement n = driver.FindElement(By.TagName("h1"));
         Console.WriteLine("Text is: " + n.Text);
      }
      [TearDown]
      public void close_Browser(){
         driver.Quit();
      }
   }
}

輸出

更新於: 2021年4月7日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告