Python and how to get text from a Selenium element WebElement object
Question:
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'
Answers:
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
Selenium get text from an element (just add ".text"):
-
For all elements of the list
tree = browser.find_elements_by_xpath(<the_XPATH>)
for i in tree:
print(i.text)
-
[ ] fetchby number
tree = browser.find_elements_by_xpath(<the_XPATH>)
print(tree[0].text)
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)
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
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'
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
Selenium get text from an element (just add ".text"):
-
For all elements of the list
tree = browser.find_elements_by_xpath(<the_XPATH>) for i in tree: print(i.text)
-
[ ] fetchby number
tree = browser.find_elements_by_xpath(<the_XPATH>) print(tree[0].text)
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)
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