karan__
karan__

Reputation: 3

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

Upvotes: 0

Views: 54348

Answers (2)

user6161210
user6161210

Reputation:

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

Upvotes: 6

user6229280
user6229280

Reputation:

You don't need to do a copy and all. All you have to do is use getText(). Try the following code:

String mytext = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div/div/div[2]/div/table/tbody/tr[2]/td[2]")).getText();
driver.findElement(By.xpath("your element path")).sendKeys(mytext);

Thank you

Upvotes: 2

Related Questions