Skip to content
Advertisement

How to get the for attribute of label element using selenium

Am trying to use Python for the first time, and working on Selenium.

Goal is to get the ID of the Input element. Am trying to work with a page that generates random ID for Input element. So cannot address that element by ID. How ever i found that the element has a label, and the label says For=”<Dynamic_ID_Of_Input>”

And it so happens the label has no other attribute either.

Here’s what the page looks like

<div class="form-input">
    <label for="labeled-input-Asrf3PAYKRKRY1veHroMKxyxf">First Name</label>
    <input type="text" id="labeled-input-Asrf3PAYKRKRY1veHroMKxyxf" name="Asrf3PAYKRKRY1veHroMKxyxf" maxlength="79" class="" value="">
</div>
<div class="form-input">
    <label for="labeled-input-7Hgp_pSJn3iqZ3T_eRwBX5I5n">Last Name</label
    <input type="text" id="labeled-input-7Hgp_pSJn3iqZ3T_eRwBX5I5n" name="7Hgp_pSJn3iqZ3T_eRwBX5I5n" maxlength="79" class="" value="">
</div>

Here’s what I have managed so far:

FName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'First Name')]//ancestor::div//input").get_attribute("id"))
print("FName_ID",FName_ID)
LName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'Last Name')]//ancestor::div//input").get_attribute("id"))
print("LName_ID",LName_ID)

the print output looks like this:

FName_ID labeled-input-Asrf3PAYKRKRY1veHroMKxyxf
LName_ID labeled-input-Asrf3PAYKRKRY1veHroMKxyxf

Am not able to figure out what is missing here. Appreciate all help.

Thank You

Advertisement

Answer

Please try this:

FName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'First Name')]/..//input").get_attribute("id"))
print("FName_ID",FName_ID)
LName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'Last Name')]/..//input").get_attribute("id"))
print("LName_ID",LName_ID)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement