如何用XPath+C#+Selenium提取元素文本节点?遇元素未找到异常
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

