簡體   English   中英

C#Selenium CSS-selector屬性不起作用

[英]C# Selenium CSS-selector attribute not working

我正在嘗試運行Selenium測試,等待某個屬性有值繼續,並在瀏覽器中檢查時(代碼檢查Ctrl + shift + Ictrl + F ),它使用css定位器定位元素,但我在運行測試時,總是會超時 - 並且元素在此之前獲得所需的值

  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方法有效 - 在ID上測試,CSS選擇器使用Class和Id(單獨)

CSS選擇器中正在使用錯誤的比較運算符。

~=運算符必須與屬性的值完全匹配。

添加屬性值的block部分,或將比較運算符更改為^=

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

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

您不需要(也不應該)在定位器中包含style=display:...以確定可見性。 硒會替您在使用.Displayed或使用ExpectedConditions並等待可見。 只需正常找到元素,例如你的兩個元素都有一個ID,所以使用By.Id("page_progress") ,就像

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

和Selenium會照顧其余的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM