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

如何用XPath+C#+Selenium提取元素文本节点?遇元素未找到异常

[Selenium C#] Can't Locate Text Node via XPath Despite Working in Chrome DevTools

Hi everyone, this is my first post on Stack Overflow! I'm a test automation engineer with years of Selenium experience, currently building automated tests using SpecFlow in Visual Studio with C#. I'm hitting a roadblock trying to extract a specific piece of text from an element—Selenium keeps throwing a "NoSuchElementException" even though my XPath works perfectly when I test it manually in Chrome.

Example HTML Structure (simplified, not original code)

<p class="day"> 
  <meta atts="somevalue"> 
  <span>Some text</span> 
  <meta atts="somevalue"> 
  <meta atts="somevalue"> 
  "Active" 
</p>

I need to extract the text "Active" from the above structure. I've written multiple XPath expressions that correctly highlight the target text node when tested in Chrome DevTools:

Working XPaths (Validated Manually)

1. //p[@class='day']/text()
2. //p[@class='day']/meta[@atts='somevalue'][3]/following-sibling::text()

All these XPaths either include or end with text(), and they uniquely target the text node I need.

Troubleshooting Steps Taken

I've ruled out several common issues:

  • No iframe nesting on the page
  • No page loading delays (I've tried explicit waits of all types, plus long Thread.Sleep() calls)
  • The element's position is fixed, so the XPath isn't dynamic
  • All other Selenium operations on the page work without issues—only this text node is problematic

Error Details

This is the line of code that fails (Driver initialization is working fine, and other elements are accessible):

String StatusVal = driver.FindElement(By.XPath("(//meta[@itemprop='closes'])[1]/following-sibling::text()")).Text;

No matter which of my validated XPaths I use, I get the same error:

OpenQA.Selenium.NoSuchElementException: Could not find element by: By.XPath: (//meta[@itemprop='closes'])[1]/following-sibling::text()

After the test fails, I go back to the same browser instance and verify the XPath again—it still correctly locates the unique text node. I'm using Selenium version 3.12.0.

Any ideas why Selenium can't pick up this text node even though the XPath is valid?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:42:18