单击特定元素后如何停止循环

时间:2016-12-20 21:16:30

标签: c# selenium selenium-webdriver automated-tests

我的网页包含具有相同xpath的系统视图。 要素:

<span class="ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest" title="System Views">Accounts Being Followed</span>
<span class="ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest" title="System Views">Accounts I Follow</span>
<span class="ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest" title="System Views">Active Accounts</span>
<span class="ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest" title="System Views">Create Personal View</span>
<span class="ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest" title="System Views">My Active Accounts</span>
<span class="ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest" title="System Views">My Connections</span>
<span class="ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest" title="System Views">System Views</span>

他们的xpath是:

//ul[contains(@class, 'ms-crm-VS-Menu')]/li/a[2]/span/nobr/span

我想打开每个视图,但想在打开特定视图后停止。我尝试使用下面的代码,但我的代码是打开所有系统视图。有人可以帮忙:

            IList<IWebElement> elements = driver.FindElements(By.XPath("//ul[contains(@class, 'ms-crm-VS-Menu')]/li/a[2]/span/nobr/span"));
        foreach (IWebElement eachelement in elements)
        {
            if (eachelement.Text.Equals("Create Personal View"))
            { break; }
            executor.ExecuteScript("arguments[0].click();", eachelement);

            }
        }

2 个答案:

答案 0 :(得分:0)

希望下面的代码段可以正常工作

List<WebElement> elements = driver.findElements(By.xpath("//span[contains(@class, 'ms-crm-VS-header-MenuItem-Title ms-crm-VS-header-MenuItem-Title-Rest')]"));
    for(WebElement ele : elements){
        //System.out.println(ele.getText());
            JavascriptExecutor executor = (JavascriptExecutor)driver;
            executor.executeScript("arguments[0].click();", ele);
            if (ele.getText().equals("Create Personal View")){
                break;
        }
    }

答案 1 :(得分:0)

试试这个:

   IList<IWebElement> elements = driver.FindElements(By.XPath("//ul[contains(@class, 'ms-crm-VS-Menu')]/li/a[2]/span/nobr/span"));
        foreach (IWebElement eachelement in elements)
        {
            if (GetInnerHtml(eachelement)=="Create Personal View")
            { break; }
            executor.ExecuteScript("arguments[0].click();", eachelement);

            }
        }

public static string GetInnerHtml(IWebElement element)
{
    var remoteWebDriver = (RemoteWebElement)element;
    var javaScriptExecutor = (IJavaScriptExecutor) remoteWebDriver.WrappedDriver;
    var innerHtml = javaScriptExecutor.ExecuteScript("return arguments[0].innerHTML;", element).ToString();

    return innerHtml;
}