Search code examples
javaselenium

How to copy and paste a value using selenium?


I am currently required to copy an order ID and then paste it into a search field.

so far I have tried:

driver.findElement (By.xpath("/html/body/main/div/div/div[2]/div/div/div[2]/div/table/tbody/tr[2]/td[2]")).sendKeys(Keys.chord(Keys.CONTROL, "c")); ,

However this fails to copy anything and when pasting it pastes what I have copied earlier by myself.

Click here


Solution

  • Hi why are you coping a particular text i.e order id in your case why not to use getText() and keep the order id in the string and then pass it in the sendKeys() it will be simple and easy to done

    String myOrderText = driver.findElement(By.xpath("ypur xpath to order id")).getText();
    

    and the use it like below

    driver.findElement (By.xpath("/html/body/main/div/div/div[2]/div/div/div[2]/div/table/tbody
    /tr[2]/td[2]")).sendKeys(myOrderText ));
    

    Also if it is mandatory to copy and paste then do it like below

    Use actions class of selenium to copy the text (order id )

    // or any locator strategy that you find suitable 
            WebElement locOfOrder = driver.findElement(By.id("id of the order id"));
    Actions act = new Actions(driver);
    act.moveToElement(locOfOrder).doubleClick().build().perform();
    // catch here is double click on the text will by default select the text 
    // now apply copy command 
    
    driver.findElement(By.id("")).sendKeys(Keys.chord(Keys.CONTROL,"c"));
    // now apply the command to paste
    driver.findElement (By.xpath("/html/body/main/div/div/div[2]/div/div/div[2]/div/table/tbody/tr[2]/td[2]")).sendKeys(Keys.chord(Keys.CONTROL, "v"));