如何检查Selenium获取的innerHTML是否包含指定字符串列表中的元素?
Solution to Check if InnerHTML Contains Any Item from a String List
Got it, let's work through this together. You already have the innerHTML from your Selenium element, and you want to check if it includes any string from your custom list. Here's a straightforward way to implement this in C#:
Full Code Example
using OpenQA.Selenium; using System.Collections.Generic; using System; // ... your existing Selenium setup code ... // Step 1: Get the innerHTML of the target element var targetElement = driver.FindElement(By.Id("list")); var innerHtml = targetElement.GetAttribute("innerHTML"); // Step 2: Define your custom string list var matchList = new List<string> { "One", "Two", "Three" }; // Step 3: Check for matches foreach (var item in matchList) { if (innerHtml.Contains(item)) { Console.WriteLine($"Match: {item}"); // Uncomment the line below if you only need the first matching item // break; } }
Key Notes
- Case Sensitivity: The default
Contains()method is case-sensitive. If you need a case-insensitive check (e.g., matching "one" or "ONE" as well), replace the condition with:if (innerHtml.IndexOf(item, StringComparison.OrdinalIgnoreCase) >= 0) - Multiple Matches: If you want to find all items in the list that appear in the innerHTML, leave out the
break;statement. If you only care about the first match, uncommentbreak;to stop the loop early. - Element Existence Check: To avoid crashes if the element with ID "list" doesn't exist, use a safer approach to retrieve the element:
var targetElement = driver.FindElements(By.Id("list")).FirstOrDefault(); if (targetElement != null) { var innerHtml = targetElement.GetAttribute("innerHTML"); // Your match-checking logic here } else { Console.WriteLine("Element with ID 'list' was not found on the page."); }
内容的提问来源于stack exchange,提问作者University Help
相关产品推荐
相关产品推荐

