How to find the value of all the id attribute of all the button elements in a web page using Selenium

521 Views Asked by At

Suppose there are multiple buttons in a web page

<button id='xyz'></button>
<button id='abc'></button>
<button id='pqr'></button>

I want the value of the id attributes of all the buttons using selenium

I am using this code

for button in driver.find_elements(by=By.XPATH,value='//button'):
   print(button.get_attribute('id'))

I am not getting any thing in the output

1

There are 1 best solutions below

0
On

Considering the HTML

<button id='xyz'></button>
<button id='abc'></button>
<button id='pqr'></button>

To extract the value of the id attributes of the <button> elements you have to induce WebDriverWait for visibility_of_all_elements_located() and using List Comprehension you can use either of the following locator strategies:

  • Using TAG_NAME:

    print([my_elem.get_attribute("id") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.TAG_NAME, "button")))])
    
  • Using CSS_SELECTOR:

    print([my_elem.get_attribute("id") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "button")))])
    
  • Using XPATH:

    print([my_elem.get_attribute("id") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//button")))])
    
  • 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