如何捕获特定元素的屏幕截图并在元素隐藏时滚动

时间:2020-07-23 09:16:16

标签: java selenium selenium-webdriver automated-tests

我在列表标签​​中有10个项目,并且想一次获取列表中一项的屏幕截图,依此类推,但是我编写的代码捕获了整个页面的屏幕截图,并且还想在剩下的“ li”元素被滚动时滚动隐藏,因此只有它应该滚动并截图。下面是代码片段

    Image Link -: https://i.stack.imgur.com/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 an 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 the 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"));
    }
    

0 个答案:

没有答案