【问题标题】:My Test always fails when I use that Xpath to search for the element in Selenium C#当我使用 Xpath 在 Selenium C# 中搜索元素时,我的测试总是失败
【发布时间】:2018-06-19 05:25:45
【问题描述】:

我正在尝试检查页面上的文本,当我检查它时,我看到:

 < div class="welcome-message">
   < h1 data-bind="text: $.t('wfo.Common:wfo.Welcome'), attr: { title:    $.t('wfo.Common:wfo.Welcome') }" title="Welcome">Welcome</h1>

在我的代码中,我使用 Xpath 来查找元素,然后尝试验证这一点

Assert.IsTrue(AdminPage.IsAt, "Not In Admin Page");

通过实现以下代码:

  public static bool IsAt { 
       get{
          var h3 = Driver.instance.FindElements(By.XPath("//div[@class='welcome-message']/h1[@title='Welcome']"));
            if (h3.Count >0)
                return true;
            return false;
        }
     }

但是当我运行该案例时,我遇到了失败:看到“不在管理页面”错误消息。

我要做的是根据搜索条件返回一个 IwebElements 列表,当找到该元素时应该返回一个真实的响应,直到现在,我假设我想匹配“真”条件.我是 Selenium 的新手,非常感谢您的帮助,非常感谢。

【问题讨论】:

  • 你有 HTML 吗?

标签: c# selenium xpath selenium-chromedriver


【解决方案1】:

我会调查的几件事:

  1. 尝试在 h1 中使用 contains 选项: //div[@class="'welcome-message']/h1[contains(@title='Welcome')

  2. Xpath 通常是查找元素方法中最不可靠的方法,如果选项可用,使用 ID、类名甚至 CSS 选择器会更好。显然,有时这是不可能的。 By.ClassName('welcome-message');

  3. 混合所有并过滤到孩子身上。 IWebElement parent = Driver.FindElement(By.CssSelector("div[class='welcome-message'])); IWebElement child = parent.FindElement(By.XPath(".//h1[@title='Welcome]"));

  4. 留出时间加载页面。 Selenium 有等待元素加载的方法,我不会详细说明,但一个例子是 here

【讨论】:

    【解决方案2】:

    试试这个:

    public static bool IsAt { 
           get{
              var h3 = Driver.instance.FindElements(By.CSSSELECTOR("div.welcome-message>h1[title='Welcome']"));
                if (h3.Count >0)
                    return true;
                return false;
            }
         }
    

    【讨论】:

    • 非常感谢@cruisepandey。我使用它并通过它: public static bool IsAt { get { var h3 = Driver.instance.FindElements(By.XPath("//*[contains(text(), 'Welcome')]"));如果 (h3!=null) 返回真;返回假; } }'
    【解决方案3】:

    我不确定.. 但我认为发生此错误是因为您的方法“IsAt”是静态,请删除此修饰符并重试

    【讨论】:

    • 对于发送建议,请在问题后面留下评论。
    【解决方案4】:

    非常感谢@cruisepandey。我使用了它并通过了它:

      public static bool IsAt
        { get
    
            {
    
         var h3 = Driver.instance.FindElements(By.XPath("//*[contains(text(), 'Welcome')]"));
    
                   if (h3!=null)
                return true;
    
                return false;
            }  
    

    当我替换你的时

    "if" 条件 (h3.Count >0) as (h3 !=null);

    我也得到了预期的结果。

    “FindElements”应该返回一个匹配搜索条件的项目列表,我不确定为什么 if (h3.Count >0) 在这种情况下不起作用?

    【讨论】:

      猜你喜欢
      • 2015-05-05
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多