首页 > 解决方案 > Ashot 没有截取正确元素的屏幕截图

问题描述

我正在尝试截取一个网页中给出的表格。以及我在代码中提供的相同元素 xpath,但是 Ashot 代码正在捕获其他位置的屏幕截图。

我也尝试过其他截图代码,

Screenshot screenshot = new AShot().takeScreenshot(driver,driver.findElement(By.xpath(webElementXpath)));

但它给了我一个错误,我可以通过阅读这个链接来修复它:https ://github.com/pazone/ashot/issues/93然后我使用了下面的代码:

WebElement myWebElement = driver.findElement(By.xpath("//center/table/tbody/*"));
        Screenshot fpScreenshot = new AShot()
                .coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver,myWebElement);

         ImageIO.write(fpScreenshot.getImage(),"PNG",new File("/Users/sanatkumar/eclipse-workspace/com.ScreenshotUtility/Screenshots/error.png"));

请帮忙,因为这段代码给了我网页随机部分的截图。我也尝试捕获其他元素,但我再次没有得到正确的屏幕截图:

请注意,我的表格在网页上并不完全可见,我必须手动向下滚动才能查看完整表格。我是否需要编写其他代码才能获得表格的完整屏幕截图?

我的网站也是基于角度的,我正在尝试使用 selenium java 实现自动化。我这样做的原因是因为在量角器中我找不到任何像 Ashot 这样的 API。如果有人知道,请告诉我。

标签: javaselenium-webdriverprotractorselenium-chromedriverashot

解决方案


通过添加一个shootingStrategy,我能够在此页面底部仅捕获具有属性 id = "post-form" 的表单元素。

来自https://github.com/pazone/ashot的文档

不同的 WebDriver 截取屏幕截图的方式不同。一些 WebDriver 提供整个页面的屏幕截图,而另一些只处理视口。

...

ShootingStrategies 中有针对不同用例的内置策略。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import javax.imageio.ImageIO;
import java.io.File;

public class Main
{
    public static void main(String args[]) throws Exception
    {
        System.setProperty("webdriver.gecko.driver", "./geckodriver");
        System.setProperty("webdriver.firefox.bin", "/usr/bin/firefox");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://stackoverflow.com/questions/54724963/ashot-is-not-taking-screenshot-of-correct-element");
        Thread.sleep(2000);
        WebElement webElement = driver.findElement(By.id("post-form"));
        Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver,webElement);
        ImageIO.write(screenshot.getImage(),"PNG",new File("/home/dan/ElementScreenshot.png"));
        Thread.sleep(2000);
        driver.quit();
    }
}

输出: 在此处输入图像描述


推荐阅读