Home > Back-end >  How to get the text from the inner span tag
How to get the text from the inner span tag

Time:02-17

Below is the html tag. I want to return the value in span as an integer in python selenium.

Can you help me out?

<span >
 <img src="/static/media/sandPot.a436d753.svg" alt="sandPot">
 <span>2</span>
</span>

CodePudding user response:

Find all the element of type span, find their value:

elements = driver.findElementsByCSS("span[]")
// loop over the elements find the text inside them
element.getAttribute("text")
// or
element.getAttrtibute("value")
// if the text or value are not empty - you have the number

CodePudding user response:

To print the text 2 you can use either of the following locator strategies:

  • Using css_selector and get_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "span.pendingCount img[alt='sandPot'][src*='sandPot']  span").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element(By.XPATH, "//span[@class='pendingCount']//img[@alt='sandPot' and contains(@src, 'sandPot')]//following::span[1]").text)
    

To extract the text 2 ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.pendingCount img[alt='sandPot'][src*='sandPot']  span"))).text)
    
  • Using XPATH and get_attribute("innerHTML"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='pendingCount']//img[@alt='sandPot' and contains(@src, 'sandPot')]//following::span[1]"))).get_attribute("innerHTML"))
    
  • Note : You have to add the following imports :

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

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


References

Link to useful documentation:

CodePudding user response:

I think this is best done with HTMLParser. You import the class, instantiate it, and feed it the tags you want it to look out for.

  • Related