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.com/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();
}
}
}输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP