Xpath select text without tagname, attribute

67 Views Asked by At

i have a weired problem and hope u can help me. Is there a good way to read the marked numbers (123456789)?

<tr>
    <td>
        <div style="width: 98%;" class="TestClass">
            <span class="highlight-label">Person: </span>
            "123456789, "
            <span class="word-break">Lastname, 
            Firstname</span>
            ", geb. 01.01.1999"
        </div>
    </td>
</tr>

This xpath:

//div[@class='TestClass'][contains(.,'123456789')]

But its not reading just the Number, its reading like everything inside the Node.

3

There are 3 best solutions below

4
Siebe Jongebloed On

You could try this:

//div[@class='TestClass'][contains(.,'123456789')]/span[1]/following-sibling::text()[1]
0
Knight On

You can use

//div/text()

This will return all text within that div

Text='
            '
Text='
            "123456789, "
            '
Text='
            ", geb. 01.01.1999"
        '

Then we need the 2nd value, so we reference the second found entry like this:

//div/text()[2]

In your case:

//div[@class='TestClass']/text()[2]

You might need to further adjust the retrieved value. But that should do the trick.

Source: https://devhints.io/xpath

0
Shawn On

Assuming you want the solution in Python, check the below code with explanation:

# Store the element first
element = driver.find_element(By.XPATH, "//div[@class='TestClass']")

# Below line will split the text by double-quote(") and then by comma(,) and store it into an array
split_text = element.text.split("\"")[1].split(",")

# print the first index of array
print(split_text[0])

Console result:

123456789