如何在Selenium中将图像复制到剪贴板?

时间:2018-07-24 20:38:57

标签: c# selenium-webdriver

我正在编写一个测试,并且我需要复制的功能实际上是将图像保存到剪贴板中,并在以后粘贴。我正在使用Selenium WebDriver v3.11.1。

我尝试使用ContextClick以多种方式复制图像,但是它从未完全实现我想要的功能,例如:

Actions rightClickAction = new Actions(driver);
rightClickAction.MoveToElement(logo).ContextClick(logo).SendKeys(Keys.ArrowDown).SendKeys(Keys.ArrowDown).SendKeys(Keys.ArrowDown).SendKeys(Keys.Enter).Build().Perform();

但是向下箭头/输入箭头从未起作用,因为它没有集中在右键单击菜单上。因此,我发现了这个错误https://bugs.chromium.org/p/chromedriver/issues/detail?id=1003,这让我觉得我不能使用上下文单击来复制图像。我也不能只按“ ctrl + c”图像。

然后我得知我可以使用剪贴板,而无法从目录中设置图像:

Clipboard.SetImage(Image.FromFile("C://Image.png"));

然后,我尝试按照以下操作进行抓屏:C# Selenium - How do you take a screenshot in Visual Studio 2015,但两者都不起作用。尝试保存屏幕截图文件并将其添加到“剪贴板”时很麻烦。

我还尝试通过使用由webdriver执行的JavaScript获取图像的base64字符串,然后将图像的base64字符串保存到文件中来从页面中抓取图像,我在这里找到:{{3} }

这也很混乱,我不确定如何将其保存到剪贴板。

那么,如何将图像保存到剪贴板?

1 个答案:

答案 0 :(得分:0)

您可以尝试类似的操作:

    driver.get("https://stackoverflow.com/");
    WebElement element = driver.findElement(By.xpath("//span[(text()='Stack Overflow') and @class='-img _glyph']"));
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height, element.getSize().height, element.getSize().width);
    Point location = element.getLocation();
    BufferedImage bufferedImage = ImageIO.read(screenshot);
    BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
    ImageIO.write(destImage, "png", screenshot);
    File file = new File("C:\\tmp\\123.png");
    FileUtils.copyFile(screenshot, file);

让我知道它是否对您有用