C# 和 Selenium:等待元素出现

seleniumcsharpautomation testingtesting tools更新于 2026/1/23 21:37:17

我们可以使用显式等待功能在 Selenium WebDriver 中等待元素出现。此功能主要用于元素在页面上可用时出现同步问题的情况。

WebDriverWait 和 ExpectedCondition 类用于显式等待的实现。我们必须创建一个 WebDriverWait 对象,该对象将调用 ExpectedCondition 类的方法。

WebDriver 会等待指定的时间,以达到预期条件。超过该时间后,将抛出异常。要等待元素出现,我们必须使用预期条件 - ElementExists。

语法

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

请尝试等待文本"关于 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://www.tutorialspoint.com/about/about_careers.htm";
      IWebDriver driver;
      [SetUp]
      public void Setup(){
          //创建 FirefoxDriver 对象
         driver = new FirefoxDriver(&"&";);
      }
      [Test]
      public void Test2(){
          //启动 URL
         driver.Navigate().GoToUrl(url);
         //识别元素并点击
         IWebElement l = driver.FindElement(By.XPath("//*[text()='Careers']"));
         l.Click();
         //ElementExists 的预期条件
         WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
         w.Until(ExpectedConditions.ElementExists(By.TagName("h1")));
         //识别元素并获取文本
         IWebElement m = driver.FindElement(By.TagName("h1"));
         Console.WriteLine("Element text is: " + m.Text);
      }
      [TearDown]
      public void close_Browser(){
         driver.Quit();
      }
   }
}

输出



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部