简体   繁体   中英

How do I copy an image to the clipboard in Selenium?

I am writing a test and the functionality I need to replicate is essentially saving a image to the clipboard and paste it later on. I am using Selenium WebDriver v3.11.1.

I have attempted using ContextClick to copy an image in many various ways and it never quite did what I wanted for example:

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

But the arrow down/enter never worked because it didn't focus on the right click menu. So then I found this bug https://bugs.chromium.org/p/chromedriver/issues/detail?id=1003 which makes me think that I can't use context click to copy an image. I also, couldn't just 'ctrl+c' the image.

I then learned that I could Clipboard which I couldn't get to set an image from my directory:

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

I then tried taking a screenshot as done here: C# Selenium - How do you take a screenshot in Visual Studio 2015 and that didn't work with either. Trying to save the screenshot file and add it to the 'clipboard' got messy.

I have also tried grabbing an image from a page by getting a base64 string of the image with JavaScript that is executed by webdriver, then saving the base64 string of the image to a file, which I found here: Using selenium to save images from page

This also got messy and I wasn't sure how to then save it to the clipboard.

So, how can I save an image to my clipboard?

You can try something similar to this:

    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);

Let me know if it works for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM