Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get text in Selenium when the text isn't neatly enclosed within a tag?

<td data-title="Docket No.">"3228"
    <div class="cursor-pointer expand-collapse-container expand-document-name">
        <div class="expand-arrow" aria-hidden="true"></div>
        <div class="collapse-arrow" aria-hidden="true"></div>
    </div>
</td>

I am using Selenium and want to get the text that follows

<td data-title="Docket No.">

which in this case is "3228"

I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lastdocket=element.find_element(By.XPATH,'//*[@data-title="Docket No."]/text()').get_attribute('innerHTML')

program crashes and I get:

 Message: invalid selector
from javascript error: {"status":32,"value":"The result of the xpath expression \"//*[@data-title=\"Docket No.\"]/text()\" is: [object Text]. It should be an element."}

I then tried getting rid of ‘text()’ from xpath expression:

lastdocket=element.find_element(By.XPATH,'//*[@data-title="Docket No."]/').get_attribute('innerHTML')

And get this when I print ‘lastdocket’:

'3228<div class="cursor-pointer expand-collapse-container expand-document-name"><div class="expand-arrow" aria-hidden="true"></div><div class="collapse-arrow" aria-hidden="true"></div></div>'

I realize I could remove thta tags the follow ‘3228’, but is there a way to return just the number???

>Solution :

The find_element method can only ever return an element, never a text node (so any XPath ending in /text() will fail).

But once you’ve found your element you can access its text property, which will return the text "as rendered", which NB is not necessarily exactly the same thing as what the XPath string() function would return; a concatenation of the text() node descendants of the element.

https://www.selenium.dev/documentation/webdriver/elements/information/#text-content

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading