首页 > 解决方案 > 在 Selenium 中找不到元素

问题描述

功能是这样的:

如果您搜索名称,搜索结果将显示在行中。在这些结果中,应选择状态为“活动”的人。要选择一个,您应该单击位于行首的链接。选择基于状态。

因此,我尝试从状态“活动”遍历到带有文本“名称在此处”的链接并得到NoSuchElementException.

代码是:

<tr height="20" class="evenListRowS1">

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<a href="javascript:void(0)" onclick="send_back('Users','b559b4f3-20ee-9bb0-320d-5a4f630dea17');">Name goes here</a>
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<a href="javascript:void(0)" onclick="send_back('Users','b559b4f3-20ee-9bb0-320d-5a4f630dea17');">email</a>
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<a href="javascript:void(0)" onclick="send_back('Users','b559b4f3-20ee-9bb0-320d-5a4f630dea17');">position</a>
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<a href="javascript:void(0)" onclick="send_back('Users','b559b4f3-20ee-9bb0-320d-5a4f630dea17');">Solutions - CRM Practice</a>
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<a href="javascript:void(0)" onclick="send_back('Users','daac0d91-4481-2204-9b62-580600287265');">Mishra</a>
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<a href="javascript:void(0)" onclick="send_back('Users','b559b4f3-20ee-9bb0-320d-5a4f630dea17');">email-address</a>
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<a href="javascript:void(0)" onclick="send_back('Users','b559b4f3-20ee-9bb0-320d-5a4f630dea17');">+1 62900*2813</a>
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
Active
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
2018-09-30 02:33 PM
</td>

<td scope="row" align="left" valign="top" class="evenListRowS1" bgcolor="">
<input type="checkbox" disabled="disabled" class="checkbox">
</td>
</tr>

我试过了

        driver.findElement(By.xpath(".//table[@class='list view']/tr[td[8][text()=\"Active\"]/td[1]")).click();

但我得到了 NoSuchElementException。

标签: javaseleniumselenium-webdriver

解决方案


所以基本上你想要这个:

  • 查找表

    //table[@class='list view']
    
  • 跳过表格一行之间的任何内容,因为它们并不重要:

    //table[@class='list view']//tr
    
  • 查找第 8 列的值所在的行Active(因为您使用的是过滤器,所以在这里通过过滤器功能更容易识别位置。同样基于您的 HTML,该列中的文本也包含新行,因此text()='Active'不会匹配,但contains会:

    <...>/td[position()=8 and contains(text(),'Active')]
    
  • 从同一行获取第 1 列。所以回到行范围..,然后选择不同的列

    <...>/td[position()=8 and contains(text(),'Active')]/../td[1]
    

一个完整的 xpath 是:

//table[@class='list view']//tr/td[position()=8 and contains(text(),'Active')]/../td[1]

推荐阅读