C#selenium web驱动程序如何在元素上循环

时间:2017-04-02 19:44:46

标签: c# selenium selenium-webdriver

这是我在C#中的代码我按下删除按钮并打开一个弹出窗口,我选择要删除的删除量,然后再次按删除它将删除。 也许在这个删除元素

时问我怎么做更为正确
PropertiesCollections.driver.FindElement (By.LinkText ("Delete")). Click ();

只要看起来它会执行删除步骤并且不继续测试

PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
new SelectElement(PropertiesCollections.driver.FindElement(By.Id("remove_shares"))).SelectByText("1");
PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();

如果出现删除按钮,我想做一个循环,它会执行删除的所有步骤,如果没有继续进行其他测试

我尝试使用此代码

   var links =   PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
             while (links = true)
              {
               PropertiesCollections.driver.FindElement(By.LinkText("Delete")).Click();
               PropertiesCollections.driver.FindElement(By.Id("remove_shares"));
               PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();
             }

但我得到错误 错误1无法将void分配给隐式类型的局部变量

1 个答案:

答案 0 :(得分:1)

第一行代码是将.Click()的返回值分配给变量links,但.Click()返回void(无)。

您想要做的逻辑是:

  1. 检查删除链接是否存在
  2. 如果是,请点击它
  3. 做事
  4. 重复1-3
  5. IReadOnlyCollection<IWebElement> links = PropertiesCollections.driver.FindElements(By.LinkText("Delete")); // gets a collection of elements with Delete as a link
    while (links.Any()) // if the collection is not empty, this evaluates to `true`
    {
        links.ElementAt(0).Click(); // click the first (and probably only?) element
        // do stuff
        PropertiesCollections.driver.FindElement(By.Id("remove_shares"));
        PropertiesCollections.driver.FindElement(By.XPath("(//button[@type='button'])[2]")).Click();
        // get the Delete links again so we can return to the start of the `while` and see if it's still not empty
        links = PropertiesCollections.driver.FindElements(By.LinkText("Delete"));
    }