Home > Net >  How to get the text from a webpage element using Selenium
How to get the text from a webpage element using Selenium

Time:08-10

I am trying to get a series of text from a web element, but unable to.

The HTML code is as follows:

<span >
  <span >SoftFEPVis (GUI): </span> == $0
  "1.6.4"
  </span>

Where SoftFEPVis (GUI): and 1.6.4 are the texts which I would like to be able extract.

I am able to locate the element, and print out its class (menu-highlight), but un-able to extract SoftFEPVis (GUI): and 1.6.4.

I tried :

Version_Number = Browser.find_element(By.XPATH,'//[@id="versionDropDown"]/div/span[3]/span').getText()

and got an error:

'WebElement' object has no attribute getText.

Please help.

CodePudding user response:

Instead of using .getText() you could use:

.get_attribute('innerText')

or

.get_attribute('innerHtml')

or

.text

If it helps, here is a more in-depth discussion of the topic: Given a (python) selenium WebElement can I get the innerText?

CodePudding user response:

getText() is a Selenium Java client method, where as from your code trials and the error message presumably you are using Selenium Python client.


Solution

To print the text SoftFEPVis (GUI): and 1.6.4 you can use the text attribute and you can use either of the following locator strategies:

  • Using css_selector and get_attribute("innerHTML"):

    print(Browser.find_element(By.CSS_SELECTOR, "span.versionInfo").text)
    
  • Using xpath and text attribute:

    print(Browser.find_element(By.XPATH, "//span[@class='versionInfo']").text)
    
  • Note : You have to add the following imports :

    from selenium.webdriver.common.by import By
    
  • Related