如何檢查元素是否存在於 C# Selenium 驅動程式中?
我們可以使用 C# 中的 Selenium Web 驅動程式檢查元素是否存在。這可以透過 **FindElements** 方法的幫助來確定。它返回一個列表,其中包含與作為該方法引數傳遞的位置匹配的元素。
如果沒有匹配的元素,則會獲取一個空列表。如果我們使用 **FindElement** 方法而不是 FindElements,則如果沒有匹配的元素,將丟擲 **NoSuchElementException**。
對於實現,我們將使用 NUnit 框架。
示例
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using System; using System.Collections.Generic; namespace NUnitTestProject1{ public class Tests{ String u = "https://tutorialspoint.tw/about/about_careers.htm"; IWebDriver d; [SetUp] public void Setup(){ //creating object of FirefoxDriver d = new FirefoxDriver(); } [Test] public void Test1(){ //launching URL d.Navigate() .GoToUrl(u); //identify elements and store it in list List<IWebElement> e = new List<IWebElement>(); e.AddRange(d.FindElements (By.XPath("//*[text()='Terms of Use']"))); //checking element count in list if (e.Count > 0){ Console.WriteLine("Element is Present"); } else { Console.WriteLine("Element is not Present"); } } [TearDown] public void close_Browser(){ d.Quit(); } } }
輸出
單擊 **執行所有測試** −
單擊 **開啟此結果的其他輸出** 連結 −
我們應該得到 **測試結果** 和 **標準輸出**。
廣告