1

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:

size
8

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...

asked Jun 13, 2020 at 21:06
1
  • Added a third approach also using document.evaluate Commented Jun 24, 2020 at 12:11

1 Answer 1

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, "")

Else:

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

answered Jun 15, 2020 at 18:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.