Selenium C# - 它从错误的表中选择一个单元格



我是使用Selenium的新手,我正在尝试从表中选择一个值。我这样做了 3 次(对于 3 个不同的表(,但如果重复此值,Selenium 会从第一个表中选择该值。

例如:

在表 1中,有一个值"X123",代码选择它,没问题。 在表 2中,还有一个值"X123"。当Selenium尝试从第二个表中选择值时,它最终会从第一个表中选择值。

映射这些表的元素真的很难,它们都是在相同的结构中构建的,所以我为此选择了 XPath 选择器,如下所示:

[FindsBy(How = How.XPath, Using = "//div[@class='k-widget k-window' and not(contains(@style, 'display: none'))]//child::div[@class='col-md-4 col-md-offset-0'][1]//child::table[@data-role='selectable']")]
private IWebElement Table1 { get; set; }
[FindsBy(How = How.XPath, Using = "//div[@class='k-widget k-window' and not(contains(@style, 'display: none'))]//child::div[@class='col-md-4 col-md-offset-0'][2]//child::table[@data-role='selectable']")]
private IWebElement Table2 { get; set; }
[FindsBy(How = How.XPath, Using = "//div[@class='k-widget k-window' and not(contains(@style, 'display: none'))]//child::div[@class='col-md-4 col-md-offset-0'][3]//child::table[@data-role='selectable']")]
private IWebElement Table3{ get; set; }

用于选择单元格的函数为:

public static void SelectMultipleGridCell(this IWebElement table, string value)
{
IList<IWebElement> tableRow = table.FindElements(By.XPath("//tr//td[text()='" + value + "']"));
new WebDriverWait(GeneralProperties.Driver, TimeSpan.FromSeconds(5))
.Until(ExpectedConditions.ElementExists(By.XPath("//tr//td[text()='" + value + "']")));
foreach (IWebElement row in tableRow)
{
if (row.IsVisible())
{
new Actions(GeneralProperties.Driver).KeyDown(Keys.Control).Click(row).KeyUp(Keys.Control).Build().Perform();
break;
}
}
}

对于使用此函数的所有其他条件,它工作正常(选择表中的多个单元格,仅选择一个单元格等(。仅当重复该值时,它才会按预期工作。我的代码是错误的还是Selenium有一些限制?

任何帮助都值得赞赏。

您需要在 XPath 前面添加一个点来搜索后代。否则,它将从根目录搜索。

public static void SelectMultipleGridCell(this IWebElement table, string value)
{
IList<IWebElement> tableRow = table.FindElements(By.XPath(".//tr//td[text()='" + value + "']"));
foreach (IWebElement row in tableRow)
{
if (row.IsVisible())
{
new Actions(GeneralProperties.Driver).KeyDown(Keys.Control).Click(row).KeyUp(Keys.Control).Build().Perform();
break;
}
}
}

最新更新