如果元素不存在,Selenium 将忽略
Selenium ignore if element not present
我的 selenium 有以下代码,我需要点击轮播图标并一张一张地获取所有图像,但有时轮播没有超过一张图像,因此箭头图标不存在并且可以点击。
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
如何处理元素不可点击的异常??
两种修复方法
使用 findElements
如果找到 return 一个 list of web element
否则 list
的 size
将是 0
try {
if (driver.findElements(By.cssSelector(".arrow-icon ")).size() > 0 ) {
System.out.println("Size is > 0 so there must be at least one web element, do some interaction below like click etc");
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
}
else {
System.out.println("Size is 0, so web element must not be present, do something here that would make it available");
}
}
catch (Exception e) {
// TODO: handle exception
}
直接使用里面有风险的代码try
try {
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
}
catch (Exception e) {
// TODO: handle exception
}
我的 selenium 有以下代码,我需要点击轮播图标并一张一张地获取所有图像,但有时轮播没有超过一张图像,因此箭头图标不存在并且可以点击。
new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click();
如何处理元素不可点击的异常??
两种修复方法
使用
findElements
如果找到 return 一个list of web element
否则list
的size
将是0
try { if (driver.findElements(By.cssSelector(".arrow-icon ")).size() > 0 ) { System.out.println("Size is > 0 so there must be at least one web element, do some interaction below like click etc"); new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click(); } else { System.out.println("Size is 0, so web element must not be present, do something here that would make it available"); } } catch (Exception e) { // TODO: handle exception }
直接使用里面有风险的代码
try
try { new WebDriverWait(driver, 40).until(ExpectedConditions.elementToBeClickable(By.cssSelector(".arrow-icon "))).click(); } catch (Exception e) { // TODO: handle exception }