C# 和 Selenium:等到元素出現
使用明確等待,我們可以在 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://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 l = driver.FindElement(By.XPath("//*[text()='Careers']"));
l.Click();
//expected condition of ElementExists
WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
w.Until(ExpectedConditions.ElementExists(By.TagName("h1")));
//identify element then obtain text
IWebElement m = driver.FindElement(By.TagName("h1"));
Console.WriteLine("Element text is: " + m.Text);
}
[TearDown]
public void close_Browser(){
driver.Quit();
}
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP