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

感情迁移 提交于 2021-02-07 03:01:48

问题


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

<span class="ocenaCzastkowa masterTooltip" style="color:#000000;" alt="Kod: 
pd1<br/>Opis: praca domowa<br/>Waga: 2,00<br/>Data: 12.09.2017<br/>Nauczyciel: 
(NAME CENSORED)">5</span>

and I want to get the value at the end (which is 5 in this case) and I have got no idea how to get it. obviously I can't use webelement.get_attribute() cause I don't know the name of the attribute.


回答1:


Try the following code:

span_element = driver.find_element_by_css_selector(".ocenaCzastkowa.masterTooltip")
span_element.text # This will return "5".

PS: Also you can use span_element.get_attribute("value").

Hope it helps you!




回答2:


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



来源:https://stackoverflow.com/questions/48139676/how-to-get-the-value-of-an-element-in-python-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!