Home > database >  Python Selenium print text
Python Selenium print text

Time:03-11

There is such HTML code on the page, I need to get its text for check, or rather 740 using Selenium.

<button data-v-3630a784="" ><div data-v-3630a784="" ><div data-v-3630a784=""  style="transform: scaleX(0.458333);"></div></div> <div data-v-3630a784="" >740</div> <!----></button>

CodePudding user response:

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

  • Using css_selector and get_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "button[class*='currency-btn'] div.num.flex.align-center.icon-mana").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element(By.XPATH, "//button[contains(@class, 'currency-btn')]//div[@class='num flex align-center icon-mana']").text)
    

To extract the text 740 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, "button[class*='currency-btn'] div.num.flex.align-center.icon-mana"))).text)
    
  • Using XPATH and get_attribute("innerHTML"):

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//button[contains(@class, 'currency-btn')]//div[@class='num flex align-center icon-mana']"))).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:

  • Related