Selenium C# 查找带有 class 和文本的元素

Selenium C# Find Element with class and text

我是测试的新手,没有接受过自动化测试方面的培训,所以如果我说了愚蠢的话,请告诉我,但我会尽力而为。

基本上我试图断言员工列表中的特定员工的状态为 'leaver'。

这是我尝试过的方法(以及具有不同 classes 的其他变体)

Assert.Equal("image-tile__badge background-color--status-leaver ng-star-inserted", Driver.FindElement(By.XPath("//*[contains(@class,'image-tile__content-header') and contains(text(),'End Date, Contract') and contains(@class, 'image-tile__badge')]")).GetAttribute("Class"));

Assert.Equal("image-tile__badge background-color--status-leaver ng-star-inserted", Driver.FindElement(By.XPath("//*[contains(@class,'image-tile__content-header') and contains(text(),'End Date, Contract')]")).FindElement(By.XPath("//*[contains(@class, 'image-tile__badge')]")).GetAttribute("Class"));
       

最后一个在状态为'new'时找到元素,但是当我将员工状态更改为'leaver'时,它仍然returns为'new'所以可能正在查看另一位状态为 'new' 的员工。

希望这是足够的信息,如果需要更多信息请告诉我(这是我第一次 post!) HTML 下图中的代码

[HTML Chrome] 上的代码 [1]: https://i.stack.imgur.com/kUxkf.png

总结:我试图断言员工“结束日期,合同”的状态为离开者(又名离开者 class “image-tile__badge background-color--status-leaver ng-星插")

根据您的屏幕截图,您可以找到所有具有 'Leaver' 特定 class 的元素;

 var leaverElmList = Driver.FindElements(By.CssSelector("div.background-color--status-leaver")).ToList();
 List<string> leaverNames = new List<string>();
 foreach (var leaverElm in leaverElmList) {
    var leaverName = leaverElm.FindElement(By.XPath(".."))
                        .FindElement(By.CssSelector("div.image-tile__content-header"));
                        .Text()
    leaverNames.Add(leaverName);
 }

根据您的屏幕截图,我填写如果您尝试使用 Xpath 会更好

var elmList = Driver.FindElements(By.Xpath("//div[contains(text(),'leaver')]")).ToList();

希望对你有所帮助 谢谢。

Enddate,与包含 Leaver 的 div 无关的合同。它的直接父级是 image-tile div

感谢大家的帮助! 我的一位开发人员设法采用@noldors 示例并对其进行了一些修改,因此这最终对我有用:

 var newElmList1 = Driver.FindElements(By.CssSelector("div.background-color--status-leaver")).ToList();
            List<string> newNames1 = new List<string>();
            foreach (var newElm in newElmList1)
            {
                var newName1 = newElm.FindElement(By.XPath(".."))
                                    .FindElement(By.CssSelector("div.image-tile__content-header")).Text;
                newNames.Add(newName1);
            }
            if (!newNames.Contains("End Date, Contract"))
            {
                throw new Exception("Exception Error on leaver Person");
            }