Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C# 및 Selenium:요소가 나타날 때까지 대기

<시간/>

명시적 대기를 사용하여 Selenium 웹 드라이버에 요소가 나타날 때까지 기다릴 수 있습니다. 페이지에서 사용할 수 있는 요소에 대한 동기화 문제가 있을 때마다 주로 사용됩니다.

WebDriverWait 및 ExpectedCondition 클래스는 명시적 대기 구현에 사용됩니다. 우리는 ExpectedCondition 클래스의 메소드를 호출할 WebDriverWait의 객체를 생성해야 합니다.

웹드라이버는 예상 기준이 충족될 때까지 지정된 시간 동안 기다립니다. 시간이 지나면 예외가 발생합니다. 요소가 존재하기를 기다리려면 예상 조건인 ElementExists를 사용해야 합니다.

구문

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

페이지에서 사용할 수 있는 텍스트 - Tutorials Point의 채용 정보가 표시될 때까지 기다려 보겠습니다. −

C# 및 Selenium:요소가 나타날 때까지 대기

예시

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(){
         //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();
      }
   }
}

출력

C# 및 Selenium:요소가 나타날 때까지 대기