Home > OS >  Handling dynamic webtable using selenium java [closed]
Handling dynamic webtable using selenium java [closed]

Time:09-22

Iam trying to click a particular company and print the company name in the console from this website http://demo.guru99.com/test/web-table-element.php# Iam getting no such element exception This is my code:

driver.findElement(By.xpath("//a[contains(text(),'Marico Ltd.')]/parent::td")).click();

CodePudding user response:

Your locator is not necessarily wrong but in this case it's not working but we can fix it. The issue is that when Selenium attempts to click an element, it finds the x-y dimensions of the element and then clicks the exact center. In this case, the exact center of the TD misses the A tag (hyperlink).

The easiest way to fix this is to just click the A tag using the locator,

//a[contains(text(),'Marico Ltd.')]

It's always a best practice to use WebDriverWait to ensure the element is ready before taking an action on it.

new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(),'Marico Ltd.')]"))).click();

CodePudding user response:

You should fetch list of elements and check the size if it exists:

List<WebElement> list = driver.findElements(By.xpath("//a[contains(text(),'Marico Ltd.')]"));
Assert.assertTrue("Text not found!", list.size() > 0);

Also you should not use /parent::td in findElement. Next you can click the element after the assertion

List.get(0).click()

CodePudding user response:

You can use a loop to search for the element by refreshing the page until displayed.

Note: If the element is not displayed it will go into infinite loop so break it at some point.

Method#1: A loop to check for 10 times whether desired element is displaying or not.

driver.get("http://demo.guru99.com/test/web-table-element.php#");
        int i = 0;
        while (i < 10) {
            if (isElementDisplayed()) {
                driver.findElement(By.xpath("//a[contains(text(),'Marico Ltd.')]/parent::td")).click();
                System.out.println("Navigated to Guru99 Bank at "   i   " iteration.");
                break;
            } else {
                driver.navigate().refresh();
                i  ;
            }
        }

Method#2: Checks and returns the boolean value as true if element exists else returns false

public static boolean isElementDisplayed() {
    try {
        driver.findElement(By.xpath("//a[contains(text(),'Marico Ltd.')]/parent::td"));
        return true;
    } catch (org.openqa.selenium.NoSuchElementException e) {
        return false;
    }
}

Output:

Navigated to Guru99 Bank at 4 iteration.
  • Related