0

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 class="pendingCount">
 <img src="/static/media/sandPot.a436d753.svg" alt="sandPot">
 <span>2</span>
</span>
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

2 Answers2

0

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
Tal Angel
  • 1,301
  • 3
  • 29
  • 63
0

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:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352