简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM