我是 Selenium 的新手,我正在尝试从表中选择一个值。我这样做了 3 次(针对 3 个不同的表),但如果重复该值,Selenium 会从第一个表中选择该值。
例如:
在表1中,有一个值“X123”,代码选择它,没有问题。 在表2中,还有一个值“X123”。当 Selenium 尝试从第二个表中选择值时,它最终会从第一个表中选择值。
映射这些表的元素确实很困难,它们都构建在相同的结构中,因此我选择了 XPath Selector,如下所示:
[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;
}
}
}
关于c# - Selenium C# - 它从错误的表中选择一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45087153/