【问题标题】:C# Selenium CSS-selector attribute not workingC# Selenium CSS-selector 属性不起作用
【发布时间】:2019-04-04 11:06:23
【问题描述】:

我正在尝试运行 Selenium 测试,它会等到某个属性具有值才能继续,并且在浏览器中检查时(代码检查 Ctrl+shift +I, ctrl+F),它使用css定位器定位元素,但我在运行测试时,总是得到一个timeout - 并且元素在该时间之前获得所需的值

  1. 检查 css 定位器在“检查代码”和搜索中是否有效
  2. 尝试了更简单的定位器 - 它可以定位 id,但无法定位属性及其值
  3. 疯狂地谷歌搜索以找到解决方案

我的代码(CMExtensionMethods.IsElementVisible == ExpectedConditions,做同样的事情):

public static WebDriverWait waitForElement = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
waitForElement.Until(CMExtensionMethods.IsElementVisible(By.CssSelector("#page_progress[style~='display:']")));


public static Func<IWebDriver, IWebElement> IsElementVisible(By identifier) {
           return (driver) =>
           {
               try {
                   return IfElementVisible(driver.FindElement(identifier));
               }
               catch(NoSuchElementException) {
                   return null;
               }
           };
       }
       // Part of the method above
       private static IWebElement IfElementVisible(IWebElement element) {
           return element.Displayed ? element : null;
       }

页面上的 HTML 代码(page_progress 样式根据网站状态而变化 - 样式可以是这样的,也可以是空的):

    <div id="page_progress" class="loading-progress" style="display: none;"> 
    </div>
    <div id="page_saveindicator" class="unsaved-changes" style="display: 
     none;"></div>

期望:在样式获得值后立即继续的代码

结果:没有找到任何东西,并且我在 5 秒(按设置)后收到超时错误,尽管元素具有属性和它应该具有的值

可能值得一提 - IsElementVisible 方法有效 - 使用 Class 和 Id(单独)在 ID 和 CSS 选择器上进行测试

【问题讨论】:

    标签: c# selenium


    【解决方案1】:

    您不需要(也不应该)在定位器中包含style=display:... 来确定可见性。当您使用 .Displayed 或使用 ExpectedConditions 并等待可见时,Selenium 会为您执行此操作。只需正常定位元素,例如你的两个元素都有一个 ID,所以使用By.Id("page_progress"),比如

    wait.Until(ExpectedConditions.ElementIsVisible(By.Id("page_progress"));
    

    Selenium 会处理剩下的事情。

    【讨论】:

    • 没想到,等我回到我的代码上去试试,我会发布结果
    • 这已经为我解决了......我以某种方式期望页面中的“可见”意味着,即使没有显示,谢谢
    【解决方案2】:

    在 CSS 选择器中使用了错误的比较运算符。

    ~= 运算符必须与属性的值完全匹配。

    要么添加属性值的block部分,要么将比较运算符更改为^=

    By.CssSelector("#page_progress[style^='display:']")
    

    更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

    【讨论】:

    • 根据 W3School 的说法,~= 不是为了确切的价值,也不是别的,而是包含该价值的所有东西。正如我提到的,它确实在浏览器中工作,所以 Selenium 应该没有区别,对吧? w3schools.com/cssref/css_selectors.asp
    猜你喜欢
    • 1970-01-01
    • 2016-08-02
    • 2014-05-22
    • 2012-01-06
    • 2013-11-21
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多