Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to get text by sibling HTML element

Tags:

c#

selenium

xpath

I have having trouble getting my specific string from an ordered list. I am using C# and Visual Studio to search a website for a specific string to then import into an Excel sheet. Specifically, this value needs to be a birthdate. My current request for the string is as follows:

driver.FindElement(By.XPath("//*[contains(text(), 'Birthdate')]")).Text;

The Ordered list that I am searching through is as follows:

<ol>                  
  <li>
        <label>Name</label>Humphries, Ryan</li>
    <li>
        <label>Birthdate</label>11/14/1992</li>
    <li>
        <label>SSN</label>

I can search for 'Birthdate' and I get that string to return to my document with my current code, however, I want the actual birthdate, not the label.

like image 881
Rinktacular Avatar asked Mar 07 '26 22:03

Rinktacular


1 Answers

The problem is, you cannot find/refer to a text node with selenium directly. The common way to approach this problem is to get the text of the parent element and "subtract" the child element's text from it.

In other words, find the li element, get the text and replace Birthdate with an empty string:

driver.FindElement(By.XPath("//li[label = 'Birthdate']")).Text.Replace("Birthdate", "")
like image 135
alecxe Avatar answered Mar 09 '26 10:03

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!