如何通过Selenium和WebDriverWait等待元素包含特定属性?

How to wait for a element to contain a specific attribute through Selenium and WebDriverWait?

如果有人可以提供帮助,我有一个 selenium 问题。我需要进入一个 URL 页面,最初该页面上的一个节点处于 "registered" 状态,X 秒后,它的状态将动态更改为 "ready" 状态。在其状态变为“就绪”状态之前,我可能会在 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 运行 的时候,这段代码从来没有工作过,它立即存在。任何想法可能是错误的?提前致谢。

可以直接等待class "model-ready"的元素存在。这是代码:

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

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

使用 FluentWait 等待状态变为 'Ready'。

 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']")); 
} 
});

要等待元素更改为就绪状态,您需要引入WebDriverWait,您可以使用以下解决方案:

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

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

像这样: webElement.waitForAttributeMatchesRegex(attribute, regex);