Home > Back-end >  Selenium webdriver: how to get all attribute values button search by some value (python)
Selenium webdriver: how to get all attribute values button search by some value (python)

Time:12-22

I want to get code & level attribute values in one button where key="a488"

this is html code which has many buttons

<button type="button" key="a435" code="11-E22." level="1"  onclick="addChild(this)"> Add</button>
<button type="button" key="a436" code="11-E22.1" level="2"  onclick="addChild(this)"> Add</button>
<button type="button" key="a488" code="11-E22.1.1" level="3"  onclick="addChild(this)"> Add</button>
<button type="button" key="a764" code="11-E22.1.2" level="3"  onclick="addChild(this)"> Add</button>

this my python code

from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()))
driver.get('https://somewebsite.com')
WebDriverWait(driver, 10).until(EC.presence_of_element_located(
                (By.XPATH, "//button[@class='btn btn-primary btn-sm']")))

and I stuck to search button attribute values where attribute key="a488"

driver.find_element(By.????, '????').get_attribute('???')

CodePudding user response:

You can try this:

ele = driver.find_element(By.XPATH, ".//button[@type='button' and @key='a488']")

code = ele.get_attribute("code")

level = ele.get_attribute("level")

CodePudding user response:

In order to retrieve element's attribute you need to wait for that element visibility (in case this is a visible element). Based on HTML you shared you can locate that element by key="a488" and then get it attributes as following:

element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'button[key="a488"]')))
code_value = element.get_attribute("code")
level_value = element.get_attribute("level")

This element can also be located with XPath as well

  • Related