长话短说 - 我有一个没有 ID 的按钮,并且有一个复合类(所以 selenium 讨厌它/找不到它)。所以我使用 XPath 选择器,效果很好
driver.findElement(By.xpath("//input[@value='Continue to Payment']")).click()
但是该按钮会根据所使用的语言而变化。
所以现在,我已经
if (driver.findElement(By.xpath("//input[@value='Continue to Payment']")).isDisplayed()){
driver.findElement(By.xpath("//input[@value='Continue to Payment']")).click();
}
else if (driver.findElement(By.xpath("//input[@value='Paiement']")).isDisplayed()){
driver.findElement(By.xpath("//input[@value='Paiement']")).click();
}
else if ( same thing as above but for another language)
但是当 Selenium 在执行第一个 if 语句后出错时:
no such element: Unable to locate element:{"method":"xpath","selector":"//a[contains(text(),'Checkout')]"}
我知道该元素不存在..所以我不希望它执行任何操作并继续执行下一个 if else 语句。 我在这里缺少什么?
最佳答案
try {
if (driver.findElement(By.xpath("//input[@value='Continue to Payment']")).isDisplayed()){
driver.findElement(By.xpath("//input[@value='Continue to Payment']")).click();
}
else if (driver.findElement(By.xpath("//input[@value='Paiement']")).isDisplayed()){
driver.findElement(By.xpath("//input[@value='Paiement']")).click();
}
else
System.out.println("Button not found");
} catch(NoSuchElementException | StaleElementReferenceException e) {
System.out.println("Impossible to click the pop-up. Reason: " + e.toString());
}
尝试上述解决方案,希望它对您有用。在您的示例中,为 else if (driver.findElement(By.xpath("//input[@value='Paiement']")).isDisplayed)
编写了错误的代码。
关于java - 如果 Selenium 驱动程序找不到元素(If - else if)继续,但它会抛出找不到元素错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566092/