Trong Selenium WebDriver C#, chờ element xuất hiện dùng Explicit Wait (chờ tường minh). Dùng khi có vấn đề đồng bộ: element chưa sẵn sàng trên trang.
Dùng class WebDriverWait và ExpectedConditions. Tạo object WebDriverWait gọi method của ExpectedConditions. WebDriver chờ trong thời gian quy định cho điều kiện đạt. Hết thời gian ném exception.
Để chờ element present, dùng expected condition ElementExists.
Cú pháp
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementExists(By.TagName("h1")));
Ví dụ: Chờ text "About Careers at Tutorials Point" xuất hiện
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System;
namespace NUnitTestProject2
{
public class Tests
{
string url = "https://www.tutorialspoint.com/about/about_careers.htm";
IWebDriver driver;
[SetUp]
public void Setup()
{
driver = new FirefoxDriver();
}
[Test]
public void Test2()
{
driver.Navigate().GoToUrl(url);
IWebElement l = driver.FindElement(By.XPath("//*[text()='Careers']"));
l.Click();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementExists(By.TagName("h1")));
IWebElement m = driver.FindElement(By.TagName("h1"));
Console.WriteLine("Element text is: " + m.Text);
}
[TearDown]
public void CloseBrowser()
{
driver.Quit();
}
}
}
Kết quả
Element text hiển thị trên console sau khi h1 xuất hiện.