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

使用Selenium获取所有以action开头的Id标签值

解决方法

你的现有代码只能定位单个id="action"的元素,还错误地尝试获取action属性(你实际需要的是元素的id属性)。要获取所有id以"action"开头的元素的id值,可以用Selenium的FindElements方法配合CSS选择器或XPath实现。

方法一:使用CSS选择器

CSS选择器[id^='action']可匹配所有id属性值以"action"开头的元素:

IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://hello/helloworld.aspx");
driver.Manage().Window.Maximize();

// 定位所有id以action开头的元素
IReadOnlyCollection<IWebElement> actionElements = driver.FindElements(By.CssSelector("[id^='action']"));

// 遍历元素,获取每个元素的id值
foreach (var element in actionElements)
{
    string actionId = element.GetAttribute("id");
    Console.WriteLine(actionId); // 输出action1、action2等目标id值
}

driver.Close();

方法二:使用XPath

XPath表达式//*[starts-with(@id, 'action')]同样能实现匹配:

IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://hello/helloworld.aspx");
driver.Manage().Window.Maximize();

// 定位所有id以action开头的元素
IReadOnlyCollection<IWebElement> actionElements = driver.FindElements(By.XPath("//*[starts-with(@id, 'action')]"));

// 遍历获取id值
foreach (var element in actionElements)
{
    string actionId = element.GetAttribute("id");
    Console.WriteLine(actionId);
}

driver.Close();

关键注意点

  • 必须用FindElements(复数形式)而非FindElement,前者返回所有匹配元素的集合,后者仅返回第一个匹配元素。
  • 如果页面元素是动态加载的,建议添加显式等待确保元素加载完成,避免找不到元素的问题:
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    wait.Until(d => d.FindElements(By.CssSelector("[id^='action']")).Count > 0);
    

内容的提问来源于stack exchange,提问作者Sharon Watinsan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:01:09