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

Java 如何通过Selenium和WebDriverWait等待元素包含特定属性?,java,selenium,selenium-webdriver,xpath,webdriverwait,Java,Selenium,Selenium Webdriver,Xpath,Webdriverwait,我有一个问题,是否有人能帮忙。我需要进入一个URL页面,页面上的节点最初处于“已注册”状态,X秒后,其状态将动态更改为“就绪”状态。在其状态移动到“就绪”状态之前,我可以在selenium执行期间继续执行下一步。 这是初始代码的html代码 <div class="icon-holder pull-left" action = "select-device" sn="FX0071234" status = "in_stock"> <i class = "...">.

我有一个问题,是否有人能帮忙。我需要进入一个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>

但是在我的selenium运行期间,这段代码从来都不起作用,它是即时存在的。有什么问题吗?请提前感谢。

您可以直接等待类为“model ready”的元素存在。下面是代码:

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

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

使用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']")); 
} 
});
Wait Wait=new FluentWait(webDriver)
.withTimeout(30,TimeUnit.SECONDS)//设置超时
.pollingEvery(2,TimeUnit.SECONDS);//设置间隔。每隔2秒检查元素状态“就绪”
WebElement foo=wait.until(新函数(){
公共WebElement应用(WebDriver驱动程序){
返回driver.findElement(By.xpath(//span[@class='model ready'和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);

与我原来的解决方案相比,这是一个更好的解决方案。我想我的解决方案“混淆”了脚本。@user3595231很高兴能够帮助你!!!如果这个/任何答案对你有帮助,请投票,以利于未来读者。
 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']")); 
} 
});
boolean status = new WebDriverWait(driver, 20).until(ExpectedConditions.attributeContains(By.xpath("//div[@class='model-holder']/span[contains(.,'200K')]"), "class", "model-ready"));