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

标签 c# selenium xpath webdriver

我是 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/

相关文章:

c# - 如何在存储库中正确处理 Linq to SQL DataContext?

xmllint 和 xpath 从 https ://mail. google.com/mail/feed/atom 解析 xml 数据

c# - 异步修饰符和等待运算符与委托(delegate)和线程有何不同?

c# - C#中的幂等接口(interface)方法

javascript - 如何使用 python 更改 html 行代码

python - 使用 Pycharm 的机器人框架——自动完成功能不起作用

C# XML --> 如何获取属于该attributes元素的属性值和xpath

java - XPath 在java中选择文档中具有指定名称的所有节点

c# - 指南针 UI 和指针

node.js - 使用 Nodejs 在 selenium 中获取 Promise Pending