I want to get text that is stored on an element. Text is not a property instead when I expand Element (in chrome's inspection [DevTools]) it has two sub-properties, span and text. it looks something like this: Web Layout I want to find only the text property not span.

I've used several way like:

elem = driver.find_element_by_xpath("/HTML/Body/li/a")
text = elem.text

But this returns:


Copying the xpath for the property, copies "html\body\li\a.text()" and finding this by xpath method throws error, obviously.

To the point: I just want to get text child property of element not span. But it returns both. Any help will be appreciated...

  • Added a third approach also using document.evaluate
    – PDHide
    Jun 24, 2020 at 12:11

1 Answer 1


Span inside is usually used for styling so, getText Assumes all child elements are part of the actual text.

Couldn't find a direct way to achieve what you are trying to do,

The workaround is to :

First solution:

just get the text from both and replace the unwanted part

 parent= driver.find_elements_by_tag_name('a')
 child= driver.find_elements_by_tag_name('span')

 parentText= parent.text
 childText= child.text

 parentText=parentText.replace(childText, "")


Second solution

parent= driver.find_elements_by_tag_name('a')
parentText= driver.execute_script("return arguments[0].firstChild.textContent", parent) 

parentText will have the value that you need

Third approach :

the script document.evaluate inside selenium execute script:

text= driver.execute_script("return document.evaluate('//a/text()', document, null, XPathResult.STRING_TYPE, null ).stringValue;");

text will have the required value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.