Getting text value of an element with XPATH
Question:
I want to grab text values of all buttons on the page like this:
all_buttons = driver.find_elements(By.TAG_NAME, 'button').getText()
But I get an error:
AttributeError: 'list' object has no attribute 'getText'
How can I extract the names of the buttons into the list?
Answers:
You can use list comprehension
to get the text of all buttons.
all_buttons = [button.text for button in driver.find_elements(By.TAG_NAME, 'button')]
find_elements
returns a list of web element objects while text
(not .getText()
, this is from Java) method can be applied on a single web element object only to extract it text content.
So, to extract texts from all the elements in the list you need to iterate over the list extracting text from each web element object as following:
all_buttons_texts = []
elements = driver.find_elements(By.TAG_NAME, 'button')
for element in elements:
element_text = element.text
all_buttons_texts.append(element_text)
Or in a shorter way, as mentioned by Fastnlight
all_buttons = [button.text for button in driver.find_elements(By.TAG_NAME, 'button')]
I want to grab text values of all buttons on the page like this:
all_buttons = driver.find_elements(By.TAG_NAME, 'button').getText()
But I get an error:
AttributeError: 'list' object has no attribute 'getText'
How can I extract the names of the buttons into the list?
You can use list comprehension
to get the text of all buttons.
all_buttons = [button.text for button in driver.find_elements(By.TAG_NAME, 'button')]
find_elements
returns a list of web element objects while text
(not .getText()
, this is from Java) method can be applied on a single web element object only to extract it text content.
So, to extract texts from all the elements in the list you need to iterate over the list extracting text from each web element object as following:
all_buttons_texts = []
elements = driver.find_elements(By.TAG_NAME, 'button')
for element in elements:
element_text = element.text
all_buttons_texts.append(element_text)
Or in a shorter way, as mentioned by Fastnlight
all_buttons = [button.text for button in driver.find_elements(By.TAG_NAME, 'button')]