【问题标题】:How to click on the aside / previous Table Cell (TD) in the same row using Selenium Webdriver with Java?java - 如何使用Selenium Webdriver和Java单击同一行中的旁边/上一个表格单元格(TD)?
【发布时间】:2020-03-18 03:40:56
【问题描述】:

我想单击动态 Web 表中存在的 Checkbox 元素,该表具有 3 个静态列(CheckBox、Description、Link)和动态行。



我能够获得复选框描述的确切文本,但我无法单击该复选框。

这是我试图达到我的期望但没有成功的脚本。可能是错误的方法。

WebElement dataTable = driver.findElement(By.id("table_id"));
List<WebElement> TDs = dataTable.findElements(By.tagName("td"));
for(WebElement td : TDs)
{
    if (!td.getText().trim().equals("text that i want to click on its checkbox"))
    continue;

    WebElement particularTd = td.findElement(By.xpath("//*[@type='checkbox']//preceding::input"));
    particularTd.click();
}

你能告诉我点击复选框的正确方法吗?

谢谢,
卡鲁纳加拉潘迪 G

【问题讨论】:

  • 您能否提供更多有关 html 的详细信息?
  • 在表格中,第一列将是一个复选框,下一列将有描述。我必须检查特定描述的复选框。在这里,复选框单元格和描述单元格都是动态 ID。如何点击特定的复选框?
  • 如果您可以分享您正在处理的 DOM 部分的屏幕截图,将能够更好地帮助您
  • 图片未显示 :(
  • @Ishan ...DOM 部分的屏幕截图... 无助于构建好的答案。对于规范的答案,相关的 HTML 是强制性的。

标签: java selenium dynamic automation webdriver


【解决方案1】:

我认为 td 只包含数据。 您可以尝试的是导航回包含表数据(td)的直接父表行(tr)。然后在那里搜索输入“复选框”。

<table>
 <tr>
  <td>
    <center><input type='checkbox'/></center>
  </td>
  <td>
    <span>Cell Desc</span>
    </td>
  <td>
    <hyperlink>
  </td>
 </tr>
</table>

要单击复选框,您可以使用 xpath:

//*[@text='Cell Desc']/ancestor::tr//input

要使 xpath 动态化,您可以获取值并使用该值

 String value = "Cell Desc";
 String xpath = "//*[@text='" + value + "']/ancestor::tr//input";

【讨论】:

  • 文本出现在“span”标签下,而“span”标签出现在“td”标签下。所以我应该使用像 //td/span[@text ='txt']/parent::tr/*[@type='checkbox'] 吗?
  • //*[@text ='txt']/ancestor::tr/*[@type='checkbox']。是的,实际的想法是导航回 tr ,然后选中该 tr 的复选框。
  • 没用。实际的表格看起来像,
    Cell Desc td>
    。同样“n”行将在那里。我需要单击 Desc 具有“提供的项目”的复选框。怎么样?
  • @Karunagara,我更新了答案中的 xpath,尝试一下。
【解决方案2】:
This worked for me please try the below code:


for(WebElement td : TDs)
{
    if (td.getText().contains("Your Text")
    td.click;
}

//if you are unable to click with td.click; use below code

for(WebElement td : TDs)
{
    if (td.getText().contains("Your Text")
{
    WebElement particularTd = td.findElement(By.xpath("//*[@type='checkbox']//preceding::input"));
    particularTd.click()
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多