Performing a copy and paste with Selenium 2

Viewed 104517

Is there any way to perform a copy and paste using Selenium 2 and the Python bindings?

I've highlighted the element I want to copy and then I perform the following actions

copyActionChain.key_down(Keys.COMMAND).send_keys('C').key_up(Keys.COMMAND)

However, the highlighted text isn't copied.

9 Answers
elem.send_keys(Keys.SHIFT, Keys.INSERT)

It works FINE on macOS Catalina when you try to paste something.

The solutions involving sending keys do not work in headless mode. This is because the clipboard is a feature of the host OS and that is not available when running headless.

However all is not lost because you can simulate a paste event in JavaScript and run it in the page with execute_script.

const text = 'pasted text';
const dataTransfer = new DataTransfer();
dataTransfer.setData('text', text);
const event = new ClipboardEvent('paste', {
  clipboardData: dataTransfer,
  bubbles: true
});
const element = document.querySelector('input');
element.dispatchEvent(event)

Solution for both Linux and MacOS (for Chrome driver, not tested on FF)

The answer from @BradParks almost worked for me for MacOS, except for the copy/cut part. So, after some research I came up with a solution that works on both Linux and MacOS (code is in ruby). It's a bit dirty, as it uses the same input to pre-paste the text, which can have some side-effects. If it was a problem for me, I'd try using different input, possibly creating one with execute_script.

  def paste_into_input(input_selector, value)
    input = find(input_selector)
    # set input value skipping onChange callbacks
    execute_script('arguments[0].focus(); arguments[0].value = arguments[1]', input, value)
    value.size.times do
      # select the text using shift + left arrow
      input.send_keys [:shift, :left]
    end
    execute_script('document.execCommand("copy")') # copy on mac
    input.send_keys [:control, 'c'] # copy on linux

    input.send_keys [:shift, :insert] # paste on mac and linux
  end

If you want to copy a cell text from the table and paste in search box,

Actions Class : For handling keyboard and mouse events selenium provided Actions Class

///

/// This Function is used to double click and select a cell text , then its used ctrl+c

/// then click on search box then ctrl+v also verify

/// </summary>

/// <param name="text"></param>

public void SelectAndCopyPasteCellText(string text)

{

  var cellText = driver.FindElement(By.Id("CellTextID"));

  if (cellText!= null)

  {

    Actions action = new Actions(driver);

    action.MoveToElement(cellText).DoubleClick().Perform(); // used for Double click and select the text

    action = new Actions(driver);

    action.KeyDown(Keys.Control);

    action.SendKeys("c");

    action.KeyUp(Keys.Control);

    action.Build().Perform(); // copy is performed

    var searchBox = driver.FindElement(By.Id("SearchBoxID"));

    searchBox.Click(); // clicked on search box

    action = new Actions(driver);

    action.KeyDown(Keys.Control);

    action.SendKeys("v");

    action.KeyUp(Keys.Control);

    action.Build().Perform(); // paste is performed

    var value = searchBox.GetAttribute("value"); // fetch the value search box

    Assert.AreEqual(text, value, "Selection and copy paste is not working");

  }

}

KeyDown(): This method simulates a keyboard action when a specific keyboard key needs to press.

KeyUp(): The keyboard key which presses using the KeyDown() method, doesn’t get released automatically, so keyUp() method is used to release the key explicitly.

SendKeys(): This method sends a series of keystrokes to a given web element.

If you are using Serenity Framework then use following snippet:

            withAction().moveToElement(yourWebElement.doubleClick().perform();
            withAction().keyDown(Keys.CONTROL).sendKeys("a");
            withAction().keyUp(Keys.CONTROL);
            withAction().build().perform();

            withAction().keyDown(Keys.CONTROL).sendKeys("c");
            withAction().keyUp(Keys.CONTROL);
            withAction().build().perform();

            withAction().keyDown(Keys.CONTROL).sendKeys("v");
            withAction().keyUp(Keys.CONTROL);
            withAction().build().perform();

            String value = yourWebElement.getAttribute("value");
            System.out.println("Value copied: "+value);

Then send this value wherever you want to send:

destinationWebElement.sendKeys(value);
            
Related