//extract the link texts of each link element
for (WebElement Page3 : linkElements3)
{
linkTitles3[k] = Page3.getText();
k++;
}
//test each link
for (String t : linkTitles3)
{
// Titles Click
driver.findElement(By.linkText(t)).click();
System.out.println("\n"+ driver.getTitle());
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
if(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).isDisplayed())
{
driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).click();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Thread.sleep(4000);
System.out.println(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/dl/dd[3]/a")).getText());
System.out.println(driver.getCurrentUrl());
driver.navigate().back();
driver.navigate().back();
}
else
{
System.out.println("No Teaching Notes Present");
driver.navigate().back();
}
}
错误:线程“main”中的异常org.openqa.selenium.NoSuchElementException:无法找到元素:{“method”:“xpath”,“selector”:“.//* [ @ ID = 'd9c1cb30-3459-4246-919d-41c5fe23de2f'] / DIV / DIV /条/ DIV / UL [1] /锂[3] /一个“}
答案 0 :(得分:1)
将if/else
部分包裹在try catch块中。因为如果页面中没有给定定位器的元素,selenium将通过异常。
try{
if(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).isDisplayed())
{
driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/div/ul[1]/li[3]/a")).click();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Thread.sleep(4000);
System.out.println(driver.findElement(By.xpath(".//*[@id='d9c1cb30-3459-4246-919d-41c5fe23de2f']/div/div/article/dl/dd[3]/a")).getText());
System.out.println(driver.getCurrentUrl());
driver.navigate().back();
driver.navigate().back();
}
else
{
System.out.println("No Teaching Notes Present");
driver.navigate().back();
}
}catch(Exception e){
System.out.println("No Teaching Notes Present");
driver.navigate().back();
}
否则您也可以使用isPresent()
代替isDisplayed()