简体   繁体   中英

How to retrieve the text from a text node within an element through Xpath, C# and Selenium

I am a test automation engineer who is Working in selenium for the last few years This is my first post in Stackoverflow.

I am trying to fetch the text from an element, but the selenium is not even identifying the element. I am using the specflow setup in visual studio and c# as the language.

Below is the sample html code (This is just a sample structure of the HTML code, not the original one) :

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

I want to fetch the text Active from the above HTML.

I wrote multiple xpaths for this, when i check this in chrome the xpaths are correct and it is highlighting the element

Xpaths trials :

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

for all the xpaths text() comes in between or at the end. all these are correct and unique when i manually checked it.

there are no frames involved in the web page i am automating. there is no page loading issue also. i have tried with with different wait statements. also tried giving a long thread.sleep().

the location of the element is always same. only the value in it will get changed. ie, the xpath for this element is not dynamic.

I am getting the error in below line. (driver is initialized properly, it is working for everything else)

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

whatever i try i am getting the below error saying element is not found,

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

The above is actual xpath, if i manually check the xpath once the test is failed in the same browser it is available there and it is unique.

ie, in my analysis my xpath is correct, there are no frames involved , there is no wait issue in the page as i am performing actions to the near by elements successfully and i am giving more than enough time for the page to load. all the normal selenium setups are done in my system and everything is working fine other than this one.

Selenium version: 3.12.0

As per the HTML you have provided to retrieve the text Active you can use ExecuteScript() method from IJavaScriptExecutor Interface as follows :

IWebElement myElem = driver.FindElement(By.XPath("//p[@class='day']"));
string myText = (string)((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].lastChild.textContent;", myElem);
Console.WriteLine(myText);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM