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

Selenium .NET中基于子元素双条件定位并点击父<li>元素

解决Selenium匹配指定书名作者元素的问题

你的XPath错误原因

  • 错误将.book-title(div元素)和.book-author(span元素)的条件合并在同一个span节点判断中,二者是独立的子元素,需分开校验
  • 未处理文本首尾的空格/换行,text()会严格匹配所有字符,包括空白符
  • 未实现忽略大小写的匹配需求

正确实现方案

方式一:修正后的XPath写法

精确匹配(区分大小写,处理空白符)

使用normalize-space()自动清理文本首尾的空格、换行,确保匹配准确性:

var matchingBooks = driver.FindElements(By.XPath($@"//li[.//div[@class='book-title' and normalize-space(text())='{b.Title.Trim()}'] and .//span[@class='book-author' and normalize-space(text())='{b.Authors.Trim()}']]"));

忽略大小写匹配

借助XPath的translate()函数统一转换文本大小写,实现忽略大小写校验:

var titleLower = b.Title.Trim().ToLower();
var authorLower = b.Authors.Trim().ToLower();
var matchingBooks = driver.FindElements(By.XPath($@"//li[translate(normalize-space(.//div[@class='book-title']/text()), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='{titleLower}' and translate(normalize-space(.//span[@class='book-author']/text()), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='{authorLower}']"));

方式二:CSS选择器+LINQ筛选(可读性更强)

如果觉得XPath语法繁琐,可以先获取所有目标li元素,再通过LINQ筛选:

var allBooks = driver.FindElements(By.CssSelector("ul.search-results li"));
var targetBook = allBooks.FirstOrDefault(li => 
    li.FindElement(By.CssSelector(".book-title")).Text.Trim().Equals(b.Title.Trim(), StringComparison.OrdinalIgnoreCase) &&
    li.FindElement(By.CssSelector(".book-author")).Text.Trim().Equals(b.Authors.Trim(), StringComparison.OrdinalIgnoreCase));

if (targetBook != null)
{
    targetBook.Click();
}

点击逻辑注意事项

无论用哪种方式,都要先判断元素是否存在再执行点击,避免空引用报错:

if (matchingBooks.Count > 0)
{
    matchingBooks[0].Click();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:25:31