html代码片段为:
<thead id="addDet:cust:th" class="emp">
<tr id="addDet:cust:ch" class="emp">
<th class="emp" scope="col" id="addDet:cust:ch:j_idt484">S. No.</th>
<th class="emp" scope="col" id="addDet:cust:ch:j_idt487">Name
<font color="#FA5882">*</font></th>
我试图将该字段填写为:
driver.find_element_by_id("addDet:cust:j_idt487").send_keys("XX")
但是我得到的错误是:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"id","selector":"psdetail:j_idt490"}
任何帮助都将是可观的。
您提供的 xpath 不指向要输入数据的字段,实际上它实际上指向列标题。这就是您无法将数据输入其中的原因。
请尝试以下 xpath 在乘客详细信息的第一行填写姓名和年龄:
- 以下代码将在第一行填写乘客姓名:
driver.find_element_by_xpath("(//tbody[@id='addPassengerForm:psdetail:tb']//input[contains(@id,'psgnName')])[1]").send_keys("ABC")
- 以下代码将填写第一行乘客的年龄:
driver.find_element_by_xpath("(//tbody[@id='addPassengerForm:psdetail:tb']//input[contains(@id,'psgnAge')])[1]").send_keys("24")
同样,为了将数据输入乘客姓名的下一行,您只需将xpath的最后一部分从[1]
调整为[2]
。
你的代码中有拼写错误。 :cust:
后你忘记了:ch:
.
修复您的选择器(Imcphers 回答/评论)后,在您尝试查找元素时,该元素是否可能不在 DOM 中? 它是动态加载的吗? 如果是这样,您可能需要使用explicit
或implicit
等待。
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
尝试 driver.implicitly_wait(10)
初始化驱动程序后
尝试使用 xpath 包含或 CSS 开头为xpath"//*[包含(. , 'S. No.)]"
id
属性值看起来非常像是动态生成的。在这种情况下,依赖它不是一个好主意。请改用元素的文本:
driver.find_element_by_xpath("//th[. = 'S. No.']")