How to store list of WebElements from a table in to a list while implementing selenium webdriver?

16,913

Solution 1

Actually what is happening mean, the return type of the

   driver.findElemnt(By.xpath("xpath"));

is the WebElement. While you adding the above code to the ArrayList it will add the WebElement. The WebElement contains the information about the

Driver Used - FirefoxDriver
Browser session value - 586a8f1f-f784-4ae7-adf5-5f920dfad8e0
locator used - xpath: .//*[@id='data_grid']/tbody/tr[1]/td[2]/a/img]

If you trying to retrieve the Web Element it will return all those things. That is what happening in your case and you are getting error while trying to click.

You can just add the Xpath locator alone in the ArrayList. It will work.

Try this

 ArrayList<String> Element1 = new ArrayList<String>();
 Element1.add(".//*[@id='data_grid']/tbody/tr["+startn+"]/td[2]/a/img");

 driver.findElement(By.xpath(Element1.get(`startn`))).click();

Solution 2

Instead of:

Naveen.findElement(By.xpath(Element1.get(start).toString())).click();

try:

Element1.get(start).click();
Share:
16,913
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to save a column of elements into a list from a table structure with the below expression on which I need to perform a click operation to validate those buttons.

    Code :

    I have the value for Total_element = 37.

    for(int start=0; start <= Total_element; start++)  
    {  
        int startn=start+1;  
        System.out.println(start);  
        List <WebElement> Element1 = new ArrayList<WebElement>() ;
    
        try{  
            Element1.add(Naveen.findElement(By.xpath(".//*[@id='data_grid']/tbody/tr["+startn+"]/td[2]/a/img")));  
        }catch(Throwable t){  
            System.out.println(t);  
        }  
        System.out.println(Element1.get(start));  
        System.out.println("The element" + start + "is :"+ Element1.get(start));  
        Naveen.findElement(By.xpath(Element1.get(start).toString())).click();  
        Naveen.findElement(By.xpath(".//*[@id='action']/a/span/div")).click();  
        System.out.println("The element" + start + "is :"+ Element1);  
        Thread.sleep(5000);  
    }
    

    Error :

    when I try to retrieve the elements from the list I get the following output :

    [[FirefoxDriver: firefox on XP (586a8f1f-f784-4ae7-adf5-5f920dfad8e0)] -> xpath: .//*[@id='data_grid']/tbody/tr[1]/td[2]/a/img]

    further which my is saying my operation is failing.