如何通过标签获取WebElement按钮
我在一个Java项目上工作,在那里我必须用Selenium做一些UAT。 我没有关于Webdevelopment的知识,所以我不确定我的问题是否可以解决。 问题是: 有一个网页,您可以在其中打勾一些单选按钮或复选框。他们都有一个字段旁边有一个文本。所以我想用Java和Selenium找到那些按钮和复选框来勾选它们。使用Firefox,我打开控制台以获取一些按钮的代码:如何通过标签获取WebElement按钮
<tr>
<td class="af_tableSelectMany_cell-icon-format OraTableBorder1111" style="">
<input id="equipmentChecker6" type="checkbox" onchange="setDirty();deselectOptions('6');selectOption('6');" value="true" name="equipmentChecker6">
</td>
<td class="af_column_cell-text OraTableBorder1111" style="text-align: left; ">Some Text1</td>
</tr>
<tr>
<td class="af_column_cell-text OraTableBorder1111"> </td>
<td class="af_column_cell-text OraTableBorder1111" style="text-align: left;">
<span class="af_selectOneRadio">
<span id="optionRadio5" class="af_selectOneRadio_content">
<input id="optionRadio5:_0" type="radio" onchange="setDirty();selectEquipment('5');" value="0" name="optionRadio5">
<label for="optionRadio5:_0">Some Text2</label>
</span>
</span>
</td>
</tr>
这是来自Page的一些代码。现在我想用id = equipmentChecker6来获取Webelement,但我只是有文本“Some Text1”。
在第二个示例中,我想通过标签对象的文本“Some Text2”来获取id = optionRadio5:_0。 有没有一种方法可以将按钮元素作为Java中的Webelements与Selenium一起使用?
THX的帮助
您可以使用类似
// For the first case
driver.findElement(By.xpath("//td[text()='Some Text1']/preceding-sibling::td/input[@type='checkbox']")).click();
// For the second case
driver.findElement(By.xpath("//label[text()='Some Text2']/preceding-sibling::input[@type='radio']")).click();
https://loadfocus.com/blog/2013/09/05/how-to-locate-web-elements-with-selenium-webdriver/
driver.findElement(By.id( “元素ID”))
所以在这种情况下:
driver.findElement(By.id ( “equipmentChecker6”))
这会工作,但我不知道ID。场景是:有人定义参数,参数是标签。所以我只有标签来找到它们引用的按钮。 – mrprinze
谢谢你的工作!有没有一个文件,我可以找到这种方法的解释,所以我可以通过我自己解决未来的类似问题? – mrprinze
其实它很常见'XPath'语法。 'before-sibling'和'following-sibling'允许你处理'DOM'中同一级别的前一个/下一个元素。我建议你把这个https://www.simple-talk.com/wp-content/uploads/imported/1269-Locators_table_1_0_2.pdf放到你的浏览器书签中,如果你要用'selenium'工作很多的话和定位器:有很多关于'XPath'和'CSS'选择器 – Andersson
谢谢! '