Java 如何使用硒复制和粘贴值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36840886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:44:30  来源:igfitidea点击:

How to copy and paste a value using selenium?

javaselenium

提问by karan__

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

我目前需要复制订单 ID,然后将其粘贴到搜索字段中。

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

点击这里

采纳答案by karan__

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

嗨,你为什么要处理一个特定的文本,即订单 ID 在你的情况下为什么不使用 getText() 并将订单 ID 保留在字符串中,然后将它传递到 sendKeys() 它将简单易行

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 )

使用 selenium 的操作类来复制文本(订单 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"));

Hope this helps you

希望这对你有帮助

回答by karan__

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

你不需要做一个副本和所有。您所要做的就是使用getText(). 试试下面的代码:

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

谢谢