47

I am trying to get the tag text content on an HTML page by using Selenium methods, but it seems method someElement.getText() is not available in Python. Is there a way?

Here's a traceback:

AttributeError: 'WebElement' object has no attribute 'getText'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 3,167
  • 6
  • 35
  • 50

4 Answers4

89

Once you locate the element you can use the text property.

Example:

for element in self.driver.find_elements_by_tag_name('img'):
       print element.text
       print element.tag_name
       print element.parent
       print element.location
       print element.size
aberna
  • 5,594
  • 2
  • 28
  • 33
  • 16
    Yes! Thank you. I found `element.get_attribute('text')` works too and it with more possibilities. – Alex Jan 19 '15 at 11:01
  • 13
    You need to be careful if the text is hidden, e.g. via CSS, on the page. In that case you need to do element.get_attribute("innerText"). See: http://yizeng.me/2014/04/08/get-text-from-hidden-elements-using-selenium-webdriver/ – Dave Potts Oct 11 '17 at 15:57
  • This reply even tough expanding on a different subject finally clarified the different objects returned by find_element and find_elements (with the plural s) : – Robert Alexander Jan 26 '22 at 16:27
  • The `.text` property (or any of the others) weirdly was not showing up in code completion. However, it did work perfectly when I used it! The same with @Alex's `get_attribute('text')`. Awesome info! – leanne Feb 23 '23 at 20:21
7

Selenium get text from an element (just add ".text"):

  1. For all elements of the list

     tree = browser.find_elements_by_xpath(<the_XPATH>)
     for i in tree:
         print(i.text)
    
  2. [ ] fetchby number

     tree = browser.find_elements_by_xpath(<the_XPATH>)
     print(tree[0].text)
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

I was in a task to extract text between the target tags, but the x.text method didn't work for me. This is because some text are saved as invisible elements. For invisible elements, use:

list1 = [x.get_attribute("innertext") for x in driver.find_element_by_xpath(xpath)]
print(list1)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aswin Babu
  • 190
  • 1
  • 8
0

Actually with Python 3 this worked for me:

obj = browser.find_element_by_xpath("the_XPATH")
print(obj.text)

Is not necessary iterate the element because launch a Traceback:

TypeError: 'WebElement' object is not iterable
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aKratos
  • 191
  • 10