Search code examples
javaselenium-webdriverautomationautomated-testsscreenshot

How to capture screenshot of all 'li' elements one after another with for loop


I have a 10 items in list tag and want to take screenshot of one item of list at a time and so on but the code i have wrote capturing whole page screenshot and also want to scroll when remaining "li" elements is hidden so then only it should scroll and take screenshot. Below is the code snipped

        Image Link -: https://i.sstatic.net/WB6Nh.png
         
        List<WebElement> list = driver.findElements(By.cssSelector(".search-results__list > li"));
        System.out.println("Total number of items :"+list.size());
        //It returns with 10 items
        
        //Scroll and capture screenshot
        for(int i= 1; i<=list.size(); i++)
        {
            WebElement element = driver.findElement(By.cssSelector(".search-results__list > li"));    
            
            //Get entire page screenshot
            File screenshots = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            BufferedImage  fullImg = ImageIO.read(screenshots);
            
            // Get the location of element on the page
            Point point = Decision_Maker.getLocation();
            
            //Get width and height of the element
            int eleWidth =  Decision_Maker.getSize().getWidth();
            int eleHeight = Decision_Maker.getSize().getHeight();
            
            //Crop the entire page screenshot to get only element screenshot
            BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
                eleWidth, eleHeight);
            
            String location = "E:\\Screenshots\\";              
            Thread.sleep(3000);
            
            //Scroll when element gets hide
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("arguments[0].scrollIntoView();", element);   
            Thread.sleep(3000);         
            FileUtils.copyFile(screenshots,new File(location +  "img" + i + ".jpg"));
        }
        

Solution

  • Try something like

     FileUtils.copyFile(screenshots,new File(location +  "img" + i + ".jpg"));