如何使用NUnit与Selenium统计DOM中ul下的li元素数量?
Counting
<li> Elements with NUnit and Selenium Got it, let's walk through exactly how to count the number of <li> elements under that specific <ul> (inside the div#selected) using NUnit and Selenium. Here's a practical, step-by-step solution with code examples:
Prerequisites
First, make sure your test project has the necessary NuGet packages installed:
Selenium.WebDriver(for core Selenium functionality)NUnitandNUnit3TestAdapter(for running and managing NUnit tests)Selenium.Support(optional, but adds handy utilities)
Full Test Example
Here's a complete NUnit test class that handles setup, counting, validation, and cleanup:
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System.Collections.Generic; namespace YourTestProjectNamespace { [TestFixture] public class ListItemCountTest { private IWebDriver _driver; [SetUp] public void TestSetup() { // Initialize ChromeDriver (ensure ChromeDriver is in your PATH or specify its file path) _driver = new ChromeDriver(); _driver.Manage().Window.Maximize(); // Navigate to the page containing your target DOM _driver.Navigate().GoToUrl("https://your-target-page-url.com"); } [Test] public void VerifyLiElementCountUnderSelectedDiv() { // Option 1: First locate the parent <ul>, then fetch its child <li> elements IWebElement targetUl = _driver.FindElement(By.CssSelector("#selected ul")); IList<IWebElement> liElements = targetUl.FindElements(By.TagName("li")); // Option 2: Directly locate all <li> elements under the target <ul> (more concise) // IList<IWebElement> liElements = _driver.FindElements(By.CssSelector("#selected ul li")); // Get the total count of <li> elements int totalLiCount = liElements.Count; // Optional: Use NUnit assertion to validate the count (matches your example's 6 elements) Assert.That(totalLiCount, Is.EqualTo(6), "The number of <li> elements doesn't match the expected count"); } [TearDown] public void TestTeardown() { // Clean up the WebDriver instance to avoid resource leaks _driver.Quit(); _driver.Dispose(); } } }
Key Details
FindElementsvsFindElement: We useFindElementsbecause it returns an empty list if no matching elements are found (instead of throwing an exception), making it safe for reliable counting.- Locating Strategies:
- CSS Selectors are clean and readable:
#selected ultargets the<ul>inside thedivwith idselected;#selected ul lidirectly targets all child<li>elements of that<ul>. - If you prefer XPath, you can use
//div[@id='selected']/ulfor the parent<ul>, or//div[@id='selected']/ul/lifor the<li>elements.
- CSS Selectors are clean and readable:
- Assertion: The
Assert.Thatline validates that the count matches your expected number (6 in the provided DOM example). This is optional but recommended to turn a simple count into a verifiable test.
内容的提问来源于stack exchange,提问作者Podpryadok Igor
相关产品推荐
相关产品推荐

