Java-driver.findElement#2

Java-driver.findElement#2,java,selenium-webdriver,Java,Selenium Webdriver,我有这个按钮: <div class="container"> <div class="alert alert-danger"> <strong>Pozor!</strong> Je třeba aktualizovat formulář kvůli změnám hodnot v personálním formuláři. <a href="#" id="newVehicles_reCompPersonnelInput" class="

我有这个按钮:

<div class="container">
<div class="alert alert-danger">
<strong>Pozor!</strong> Je třeba aktualizovat formulář kvůli změnám hodnot v personálním formuláři.  <a href="#" id="newVehicles_reCompPersonnelInput" class="btn btn-xs btn-danger pull-right reCompPersonnelInput">Přepočítat</a>       
</div>
</div>

波佐Je třeba Aktualizova formulákvůli zmánám hodnot v personáln m formulái。
使用
WebElement prepositat=driver.findElement(By.id(“newVehicles\u recompersonnelinput”))查找它没有问题


但该按钮仅在某些情况下存在。如何避免NoTouchElementException?

您可以使用
findelelements
,如果元素不存在,它只会返回一个空列表,省去昂贵的
try-catch

try
{
    WebElement prepocitat = 
    driver.findElement(By.id("newVehicles_reCompPersonnelInput"));
}
catch(NoSuchElementException)
{
    do your action here
}
List<WebElement> prepocitat = driver.findElements(By.id("newVehicles_reCompPersonnelInput"));
if (prepocitat.size > 0) {
    prepocitat.get(0).click();
}
List prepositat=driver.findElements(By.id(“新车重新编译”);
如果(前置大小>0){
获取(0)。单击();
}

您可以进行fluentWait

 static Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(elementWaitTime, SECONDS)
    .pollingEvery(2,SECONDS)
    .ignoring(NoSuchElementException.class);

 public WebElement getAnyElement(By byLocator){

  return wait.until(ExpectedConditions.visibilityOfElementLocated(locator));       

  }

Anand建议的工作解决方案:

try 
{ 
WebElement prepocitat = driver.findElement(By.id("newVehicles_reCompPersonnelInput")‌​);
prepocitat.click()‌​;Thread.sleep(1000); 
} 
catch (org.openqa.selenium.NoSuchElementException e) { }

谢谢,几乎完美:-)试试{WebElement prepositat=driver.findelelement(By.id(“newVehicles\u recompersonnelinput”);prepositat.click();Thread.sleep(1000);}catch(org.openqa.selenium.NoSuchElementException e){}好的,太棒了如果您能将此答案标记为您问题的答案,我们将不胜感激:)请参阅盖伊的答案,以获取最佳实践。他说:但按钮仅在某些情况下存在。如何避免NosTouchElementException?正如在标记上所理解和看到的:“但按钮仅在某些情况下存在。我如何避免NosTouchElementException?”意味着他正在寻找一种方法来单击该元素,因为它有时工作,有时抛出异常。请澄清您的问题。您是否正在处理基于特定行为弹出的警报?或者元素是否在某些运行中可见且不一致?这是状态的最佳实践<代码>查找元素不应用于查找非当前元素,使用FieldEngby(by),而断言零长度响应。 thRead。睡眠不是一个好的实践,考虑使用隐式或显式等待。
try 
{ 
WebElement prepocitat = driver.findElement(By.id("newVehicles_reCompPersonnelInput")‌​);
prepocitat.click()‌​;Thread.sleep(1000); 
} 
catch (org.openqa.selenium.NoSuchElementException e) { }