当在硒中找不到元素时如何执行脚本

本文关键字:何执行 执行 脚本 找不到 元素 | 更新日期: 2023-09-27 18:17:40

  • 我正在使用下面的代码片段来验证元素的可见性。 每当MyBuyer元素不存在时,Selenium就会花费太多时间并且不继续下一步。
  • 在下面的脚本捕获块中,打印消息"我的买家链接未显示",但不移动到脚本的后续步骤。
WebElement Find=null;
Find=driver.findElement(By.xpath("//*[@id='headerapp']/div/div/ul/li[2]/a"));
if(Find!=null && Find.isDisplayed()){
    Actions action=new Actions(driver);
    action.moveToElement(Find).build().perform();
    driver.findElement(By.xpath("//*[@id='headerapp']/div/div/ul/li[2]/ul/li[1]/a")).click();
    driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
}
Thread.sleep(2000);
WebElement mybuyers=null;
try{
    mybuyers=driver.findElement(By.xpath("//a[contains(., 'My Buyers')]"));
    if(mybuyers!=null && mybuyers.isDisplayed()){
        Actions action=new Actions(driver);
        action.moveToElement(mybuyers).build().perform();
        mybuyers.click();
        driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
    }
}catch(Exception e){
    System.out.println("My Buyers link is not displayed");
}
finally{
    driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
}
Thread.sleep(2000);
WebElement mylisting=null;
try{
    mylisting=driver.findElement(By.xpath("//a[contains(., 'My Listing')]"));
    if(mylisting!=null && mylisting.isDisplayed()){
        Actions action=new Actions(driver);
        action.moveToElement(mylisting).build().perform();
        mybuyers.click();
        driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
    }
}catch(Exception e){
    System.out.println("My Listing link is not displayed");
}
finally{
    driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
}

当在硒中找不到元素时如何执行脚本

像这样使用 FindElements 而不是 FindElement:

 Boolean isMyBuyersPresent = driver.findElements(By.yourLocator).size() > 0

if(isMyBuyersPresent)
{
    //You can re-find as below, or refactor the code and 
    //create a list in the above snippet and grab the first element here
    mybuyers= driver.findElements(By.yourLocator)
}