You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查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, uncomment break; 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:55:05