Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

C# และ Selenium: รอจนกว่า Element จะปรากฏ (Wait Until Element Present)


สามารถรอจนกว่า Element จะปรากฏใน Selenium WebDriver ได้ด้วย Explicit Wait ใช้หลักเมื่อมีปัญหา Synchronization (Element ยังไม่พร้อมบนหน้า)

ใช้ Class WebDriverWait และ ExpectedConditions สร้าง Object WebDriverWait เรียกเมธอดของ ExpectedConditions

WebDriver รอเป็นเวลาที่กำหนดจนเงื่อนไขเป็นจริง หากเวลาหมดจะโยน Exception เพื่อรอ Element ให้ Present ใช้ Expected Condition: ElementExists

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.Support.UI;

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 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 CloseBrowser() => driver.Quit();
    }
}

ผลลัพธ์

Element text is: About Careers at Tutorials Point