selenium expand collapse treeview C#

selenium expand collapse treeview C#

我刚开始使用 selenium C#。 我有一个树视图,它的位置不一致,所以如果它没有展开我想展开它,如果它已经展开它应该保持原样。类似崩溃。

这是树展开的时候

<div class="rtTop">
     <span class="rtSp"></span>
     <span class="rtMinus"></span>
     <span class="rtIn">Roles</span>
</div>

这是崩溃的时候

<div class="rtTop">
     <span class="rtSp"></span>
     <span class="rtPlus"></span>
     <span class="rtIn">Roles</span>
</div>

我目前正在使用

public static string treeviewExpand( string treeviewExpandButton)
{
    treeviewExpandButton = "//span[text()='" + treeviewExpandButton + "']/preceding-sibling::span[@class='rtPlus']";
    return treeviewExpandButton;
}
public static string treeviewCollapse(string treeviewCollapseButton)
{
    treeviewCollapseButton = "//span[text()='" + treeviewCollapseButton + "']/preceding-sibling::span[@class='rtMinus']";
    return treeviewCollapseButton;
}

如果调用适当的操作,上述 xpath 工作正常。 但我想要一个通用的动作函数来展开和折叠树,而不管它的当前状态。

我尝试使用文本获取树视图节点的当前 class 名称。 在这里,我试图获取当前的 class "rtPlus" 或 "rtMinus" 但是当我尝试使用标签名称作为跨度获取前一个兄弟时,我得到的标签跨度为 class "rtsp" 而不是 class "rtPlus" 或 "rtMinus" 即使检查显示其前面的兄弟跨度有 class "rtPlus" 或 "rtMinus"

我正在使用

public static string treeviewExpandCollapse(string treetext)
{
    treetext= "//span[text()='" + treetext+ "']";
    IWebElement element;
    element = driver.FindElement(treetext).FindElement(By.XPath("./preceding-sibling::span"));
    string calsss = element.GetAttribute("class");

    Thread.Sleep(2000);
}

XPath 可能很棘手,尤其是当您开始将多个 FindElement 和 XPath 链接在一起时。对于您的场景,我会通过仅使用一个 XPath 来保持简单:

"//span[text()='" + text + "']/parent::div/span[2]"

解释:

  • //span[text()='" + text + "'] - select <span> 与给定的 text
    • <span class="rtIn">Roles</span>
  • /parent::div - select <span> 的 parent
    • <div class="rtTop">
  • /span[2] - 在索引 2 的 parent、select 和 <span> 中(无论 <span> 是展开还是折叠)
    • <span class="rtPlus"></span>

代码:

IWebElement element = driver.FindElement(
    By.XPath("//span[text()='" + text + "']/parent::div/span[2]"));