Selenium 웹드라이버에서는 명시적 대기(Explicit Wait)를 사용하여 특정 요소가 페이지에 나타날 때까지 기다릴 수 있습니다. 명시적 대기는 주로 페이지 로딩 속도 차이 등으로 인해 요소와의 동기화 문제가 발생할 때 활용됩니다.
명시적 대기는 WebDriverWait 클래스와 ExpectedConditions 클래스를 통해 구현합니다. 먼저 WebDriverWait 객체를 생성하고, 이 객체가 ExpectedConditions 클래스의 메서드를 호출하도록 작성해야 합니다.
웹드라이버는 지정된 시간 동안 설정된 조건이 충족될 때까지 대기하며, 제한 시간이 경과한 후에도 조건이 충족되지 않으면 예외가 발생합니다. 요소가 존재할 때까지 대기하려면 ElementExists라는 예상 조건(Expected Condition)을 사용하면 됩니다.
문법(Syntax)
WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
w.Until(ExpectedConditions.ElementExists(By.TagName("h1")));이번 예제에서는 페이지에 "About Careers at 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("요소의 텍스트: " + m.Text);
}
[TearDown]
public void close_Browser(){
driver.Quit();
}
}
}핵심 포인트
- 명시적 대기는 특정 조건이 충족될 때까지만 대기하므로, 고정된 시간을 무조건 기다리는
Thread.Sleep()방식보다 효율적입니다. - 조건이 제시간 내에 충족되지 않으면
TimeoutException이 발생하므로, 필요에 따라 try-catch 블록으로 예외 처리를 추가하는 것이 좋습니다. ElementExists외에도ElementIsVisible,ElementToBeClickable등 다양한 예상 조건을 상황에 맞게 활용할 수 있습니다.
실행 결과
