1

Can anyone help me out with a relative XPath expression that will verify a text that is contained inside multiple span elements

<div id="id1">
  <span >Hello </span>
  <span class="class2">World </span>
</div>`

I am new to selenium and I haven't used XPath that much. I need an XPath that will return the text "Hello World" in one line(preferred outcome) or even a list of text values.

andrei1986
  • 25
  • 9

2 Answers2

3

This XPath,

normalize-space(//div[@id="id1"])

will return the space-normalized, string-value of the first div with an id attribute value equal to id1,

Hello World

as requested.

Notes

  • Key concept is that of the string-value of an element.

  • If you cannot be certain that there's only a single div element with id="id1", or if you wish your XPath to work with 2.0+, explicitly select only the first one to pass to normalize-space():

    normalize-space((//div[@id="id1"])[1])
    

See also

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • 1
    Brilliant answer! Never tried (or needed) to used normalize-space before but it works very well - one quick note is in selenium you use xpaths for element identification rather than returning text - wrap that with an assert and your in business: `//div[normalize-space((//div[@id="id1"]))="Hello World"]` - if you find that element, your text exists and assert would pass – RichEdwards Aug 19 '20 at 14:36
  • @RichEdwards: Thank you for the compliment and the helpful Selenium addendum. – kjhughes Aug 19 '20 at 14:44
1

I don't think you need an xpath here.

For the source you provided, you can use .text against the parent div and it returns the text.

This simple page:

<html>
    <body>
        <div id="id1">
            <span >Hello </span>
            <span class="class2">World </span>
        </div>
    </body>
</html>

This code:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(r"C:\Git\PythonSelenium\TextSplitOverTags.html")

print(driver.find_element_by_id('id1').text)

output looks like in the console...

getting text from selenium

When you get the output you can verify the text is as expected.

RichEdwards
  • 3,423
  • 2
  • 6
  • 22