Java selenium 使用 xpath 查找元素 [英] Java selenium find element with xpath
问题描述
我正在开发一个网络应用程序,我需要找到一个特定的元素,但我无法用我的 xpath 找到它.这是我试图找到元素的 html 代码
<tr><th class="详细信息"><label>名称</label></th><td class="数据"><div id="..."><div id="..."></div><input id="..." type="text"></td></tr>.....
我成功找到了它,但是当我注意到 ID 是自动生成的时,我被卡住了.我试图解决这个问题,找到包含文本名称"的标签,然后找到兄弟姐妹但什么也没有.这是我的 xpath:
//*[text()[contains(.,'Name')]]/../following-sibling::td
你应该尝试使用下面的 xpath
:-
String xpath = "(.//label[text() = 'Name']/following::input)[1]";
或
String xpath = ".//label[text() = 'Name']/../following-sibling::td//input";
或
String xpath = "(.//input[preceding::label[text() = 'Name'])[1]";
或
String xpath = ".//input[ancestor::td[preceding-sibling::th/label[text() = 'Name']]]";
您可以使用上述 xpath
中的任何一个来查找所需的输入元素,如下所示:-
browser.findElement(By.xpath(xpath));
all I'm delevoping a web app and I need to find a specific element but I can't find it out with my xpath. This is the html code where I'm trying to find the element
<table>
<tr>
<th class="details">
<label>Name</label>
</th>
<td class="data">
<div id="...">
<div id="..."></div>
<input id="..." type="text">
</div>
</td>
</tr>
..........
</table>
I successfully found it but when I noticed that the ids are autogenerated I got stuck. I tried to solve this problem finding the label which contains the text 'Name' and then finding the siblings but nothing. This is my xpath:
//*[text()[contains(.,'Name')]]/../following-sibling::td
You should try using below xpath
:-
String xpath = "(.//label[text() = 'Name']/following::input)[1]";
Or
String xpath = ".//label[text() = 'Name']/../following-sibling::td//input";
Or
String xpath = "(.//input[preceding::label[text() = 'Name'])[1]";
Or
String xpath = ".//input[ancestor::td[preceding-sibling::th/label[text() = 'Name']]]";
You can use anyone of these above xpath
to find desire input element as below :-
browser.findElement(By.xpath(xpath));
这篇关于Java selenium 使用 xpath 查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!