简体   繁体   English

如何使用 selenium 获取 label 元素的 for 属性

[英]How to get the for attribute of label element using selenium

Am trying to use Python for the first time, and working on Selenium.我第一次尝试使用 Python,并致力于 Selenium。

Goal is to get the ID of the Input element.目标是获取 Input 元素的 ID。 Am trying to work with a page that generates random ID for Input element.我正在尝试使用为 Input 元素生成随机 ID 的页面。 So cannot address that element by ID.因此无法通过 ID 来处理该元素。 How ever i found that the element has a label, and the label says For="<Dynamic_ID_Of_Input>"我怎么发现该元素有一个 label,而 label 说 For="<Dynamic_ID_Of_Input>"

And it so happens the label has no other attribute either.碰巧 label 也没有其他属性。

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:打印 output 看起来像这样:

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谢谢你

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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