How to get the value of an element in Python + Selenium?

前端 未结 2 599
感动是毒
感动是毒 2021-02-15 12:16

I have got this HTML element in my Python (3.6.3) code (as Selenium webelement of course):



        
2条回答
  •  旧巷少年郎
    2021-02-15 12:52

    To print the textContent i.e. 5 you can use either of the following Locator Strategies:

    • Using css_selector:

      print(driver.find_element(By.CSS_SELECTOR, "div.ocenaCzastkowa.masterTooltip").text)
      
    • Using xpath:

      print(driver.find_element(By.XPATH, "//span[@class='ocenaCzastkowa masterTooltip']").text)
      

    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:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ocenaCzastkowa.masterTooltip"))).text)
      
    • Using XPATH:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='ocenaCzastkowa masterTooltip']"))).text)
      
    • 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

提交回复
热议问题