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
JavaScript
x
9
1
<div class="form-input">
2
<label for="labeled-input-Asrf3PAYKRKRY1veHroMKxyxf">First Name</label>
3
<input type="text" id="labeled-input-Asrf3PAYKRKRY1veHroMKxyxf" name="Asrf3PAYKRKRY1veHroMKxyxf" maxlength="79" class="" value="">
4
</div>
5
<div class="form-input">
6
<label for="labeled-input-7Hgp_pSJn3iqZ3T_eRwBX5I5n">Last Name</label
7
<input type="text" id="labeled-input-7Hgp_pSJn3iqZ3T_eRwBX5I5n" name="7Hgp_pSJn3iqZ3T_eRwBX5I5n" maxlength="79" class="" value="">
8
</div>
9
Here’s what I have managed so far:
JavaScript
1
5
1
FName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'First Name')]//ancestor::div//input").get_attribute("id"))
2
print("FName_ID",FName_ID)
3
LName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'Last Name')]//ancestor::div//input").get_attribute("id"))
4
print("LName_ID",LName_ID)
5
the print output looks like this:
JavaScript
1
3
1
FName_ID labeled-input-Asrf3PAYKRKRY1veHroMKxyxf
2
LName_ID labeled-input-Asrf3PAYKRKRY1veHroMKxyxf
3
Am not able to figure out what is missing here. Appreciate all help.
Thank You
Advertisement
Answer
Please try this:
JavaScript
1
5
1
FName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'First Name')]/..//input").get_attribute("id"))
2
print("FName_ID",FName_ID)
3
LName_ID = (driver.find_element_by_xpath("//label[contains(text(), 'Last Name')]/..//input").get_attribute("id"))
4
print("LName_ID",LName_ID)
5