Search code examples
javaseleniumselenium-webdriverui-automationbrowser-automation

Delete a record from web table scenario in Selenium Webdriver


I am writing an automation script and one of the scenarios I wish to automate is to delete a record from grid, now what I am doing is finding the xpath of the list of delete buttons in the grid, and I'm hitting an 'if' condition where I state that if the delete button is displayed on page delete the first record or else driver.close(); but I guess Selenium isn't checking the condition, it is directly showing me NoSuchElement exception. Can someone please suggest me a better way or some other alternative to automate such a scenario. The code I'm using:=

    //resourceSchedulePage - Class object
    //clickDeleteResourceScheduleDataBtn() - method that returns the WebElement
    schedulerPage.clickResourceSchedule().click();
    logger.info("Resource schedule link is clicked");
    Thread.sleep(500);
    if(resourceSchedulePage.clickDeleteResourceScheduleDataBtn().isDisplayed())
    {
        resourceSchedulePage.clickDeleteResourceScheduleDataBtn().click();
        Thread.sleep(500);
    }
    else
    {
        driver.close();
    }

Implementation :

@FindBy(xpath="//*[@id=\"gridResourceSchedule\"]//td[6]/a[2]") 
WebElement deleteResourceScheduleBtn; 

public WebElement clickDeleteResourceScheduleDataBtn() throws InterruptedException { 
      synchronized (driver) { 
          driver.wait(1000); } 
     return deleteResourceScheduleBtn; }

Solution

  • As explained by @pburgr, here is the implementation for findElements

    if (driver.findElements(By.xpath("Delete button xpath")).size() > 0 ) {
        System.out.println("Delete button is avilable");
        // you can click on delete here, or whatever you wanna do. 
    }
    else {
        System.out.println("Delete button isn't avilable");
        driver.close();
    }
    

    also there is a way to handle this situation which is try catch block.