【问题标题】:How to wait for a element to contain a specific attribute through Selenium and WebDriverWait?如何通过 Selenium 和 WebDriverWait 等待元素包含特定属性?
【发布时间】:2018-07-10 04:28:48
【问题描述】:

如果有人可以提供帮助,我有一个硒问题。我需要进入一个 URL 页面,该页面上的节点最初处于“已注册”状态,X 秒后,其状态将动态更改为“就绪”状态。在它的状态变为“就绪”状态之前,我可能会在 selenium 执行期间继续下一步。 这里是初始代码的html代码,

<div class="icon-holder pull-left" action = "select-device" sn="FX0071234" status = "in_stock">
   <i class = "...">...</i>
   <div class="model-holder">
       <span class="model-registered">200K</span>
   </div>
   <div class="active-holder">...</div>
</div>

这是 X 秒后更新的 html 代码,

<div class="icon-holder pull-left" action = "select-device" sn="FX0071234" status = "discovered">
   <i class = "...">...</i>
   <div class="model-holder">
       <span class="model-ready">200K</span>
   </div>
   <div class="active-holder">...</div>
</div>

我想新建一个 WebDriverWait() Obj 以等待更改发生。这是我的代码:

new WebDriverWait(driver, 50).until(ExpectedConditions.attributeContains(
                By.xpath("//span[@class = 'model-registered' and text() = '200K']"), "class", "model-ready"));

但是在我的 selenium 运行时,这段代码永远不会工作,它会立即存在。有什么想法可能是错的吗?提前致谢。

【问题讨论】:

    标签: java selenium selenium-webdriver xpath webdriverwait


    【解决方案1】:

    要等待元素变为ready状态,你需要诱导WebDriverWait,你可以使用以下解决方案:

    boolean status = new WebDriverWait(driver, 20).until(ExpectedConditions.attributeContains(By.xpath("//div[@class='model-holder']/span[contains(.,'200K')]"), "class", "model-ready"));
    

    【讨论】:

    • 与我原来的解决方案相比,这是一个更好的解决方案。我猜我的“混淆”了脚本。
    • @user3595231 很高兴能为您提供帮助!!!如果此/任何答案对您有帮助,请为未来读者的利益投票。
    【解决方案2】:

    您可以直接等待具有“模型就绪”类的元素存在。代码如下:

    new WebDriverWait(driver, 50).until(ExpectedConditions.ElementExists(
                By.xpath("//span[@class = 'model-ready' and text() = '200K']")));
    

    如果这不起作用,请告诉我。

    【讨论】:

      【解决方案3】:

      使用 FluentWait 等待状态更改为“就绪”。

       Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver)
      .withTimeout(30, TimeUnit.SECONDS) // set the timeout
      .pollingEvery(2, TimeUnit.SECONDS); // set the interval. Checks every 2sec's for the element status 'ready'
      
      WebElement foo = wait.until(new Function() { 
      public WebElement apply(WebDriver driver) { 
      return driver.findElement(By.xpath("//span[@class = 'model-ready' and text() = '200K']")); 
      } 
      });
      

      【讨论】:

        【解决方案4】:

        您也可以使用方法waitForAttributeMatchesRegex 等待定位属性,直到它与某个特定模式匹配。

        类似这样的: webElement.waitForAttributeMatchesRegex(attribute, regex);

        【讨论】:

          猜你喜欢
          • 2021-08-07
          • 1970-01-01
          • 2020-09-16
          • 1970-01-01
          • 2021-04-01
          • 2019-12-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多