我需要从用户界面列表中选择元素APPLICATION。这个元素的html代码(在html中我有10个这样的元素)是:
<tr id="4676856" class="menuItem" orientation="vertical" collectionid="tr4" radioid="12">
<td id="ItemL" class="left" data-click="[["runScript",["switchApplication('myapp')"]]]" data-ctl="nav">
<div class="menuRB"/>
</td>
<td id="ItemM" class="middleBack" tabindex="0" data-click="[["runScript",["switchApplication('myapp')"]]]" data-ctl="nav">**APPLICATION**</td>
<td id="ItemR" class="rightEdge" data-click="[["runScript",["switchApplication('myapp')"]]]" data-ctl="nav"/>
我从未使用过这样的脚本,如何使用 selenium webdriver 找到这样的元素?
我已经尝试过
driver.findElement(By.xpath(".//*[@id='yui-gen0']/div[6]/table/tbody/tr[12]/td[1]")).click();
最佳答案
请显示与您的 XPath 匹配的 HTML 代码(yui-gen0
等在哪里?)
根据您提供的信息,您可能需要避免一些问题:
- 尽量避免使用 div[6]、tr[12],使用有意义的东西代替索引
- 如果是自动生成的,请勿使用
yui-gen0
- 保持 HTML ID 唯一,例如
id="ItemM"
。如果它们是唯一的,则直接使用它们
我建议尝试以下操作(我们需要您显示更多 HTML 以避免使用 div[6]、tr[12]):
// find by text '**APPLICATION**'
driver.findElement(By.xpath(".//*[@id='yui-gen0']/div[6]/table/tbody/tr[12]/td[text()='**APPLICATION**']")).click();
// find by class name (if it's the only one)
driver.findElement(By.xpath(".//*[@id='yui-gen0']/div[6]/table/tbody/tr[12]/td[@class='middleBack']")).click();
// find by class name (if there are others)
driver.findElement(By.xpath(".//*[@id='yui-gen0']/div[6]/table/tbody/tr[12]/td[contains(@class, 'middleBack')]")).click();
// find by id, which should be unique, if it's not, your HTML is bad
driver.findElement(By.xpath(".//*[@id='ItemM']")).click();
关于java - 如何选择由脚本 selenium webdriver 生成的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19771874/