[SOLVED] Selenium Python: how to get a list of all strings in a tag

Issue

I am trying to get text ("Get this text") inside the following html using this Xpath: "//span[@id='myanswer']/text()[7]". It finds the text on the website when I put it in the cntrl+F field in the inspect html part, but when I try to print the output in my python code it returns nothing. Also doing something like

driver.find_element(By.XPATH,"//span[@id='myanswer']").text,

also returns nothing. So I’m thinking maybe appending all those strings into a list and printing the last element of that list? Is there any way of printing out this last string?

<span id="myanswer">
    <br>
    <br> 
    " [&nbsp;"
    <b>tU</b>
    " method Response ]"
    <br>
    "&nbsp;"
    <span class="text-success"><i class="fa  fa-angle-double-right"></i></span>  
    <strong></strong> 
    "&nbsp;" 
    <span class="text-secondary"><i>string</i></span> 
    <b>:</b> 
    "
    &nbsp;Get this text"
    <br>
    <br>
</span>

Solution

So I’m thinking maybe appending all those strings into a list and
printing the last element of that list

  • This is one of the good ways to deal with this text node.

If

driver.find_element(By.XPATH,"//span[@id='myanswer']").text

did not return anything then there could multiple reason:

1.

//span[@id='myanswer'] is not unique in HTMLDOM. 

Steps to check for uniqueness:

Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

  1. Maybe you are missing a delay, Please put a sleep or use Explicitwait like below:

    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@id='myanswer']"))).get_attribute('innerText')
    

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Answered By – cruisepandey

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *