如何通过 selenium-webdriver 和 Java 从剪贴板粘贴文本?

Ash*_*tha 6 clipboard selenium webdriver paste selenium-webdriver

我想要一个复制到剪贴板的文本,并希望将其粘贴到文本字段中。

有人可以让我知道怎么做吗

例如:-

driver.get("https://mail.google.com/");

driver.get("https://www.guerrillamail.com/");
driver.manage().window().maximize();
driver.findElement(By.id("copy_to_clip")).click(); -->copied to clipboard
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("nav-item-compose")).click(); 

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.name("to")).???;//i have to paste my text here that is copied from above
Run Code Online (Sandbox Code Playgroud)

opt*_*per 6

如果单击 id 为“copy_to_clip”的按钮确实将内容复制到剪贴板,那么您可以使用键盘快捷键选项。我想,您可能还没有尝试过模拟 CTRL + v 组合。通过单击激活您的目标文本字段,然后使用您的快捷方式。这可能会有所帮助。

代码片段:

driver.findElement(By.name("to")).click(); // Set focus on target element by clicking on it

//now paste your content from clipboard
Actions actions = new Actions(driver);
actions.sendKeys(Keys.chord(Keys.LEFT_CONTROL, "v")).build().perform();
Run Code Online (Sandbox Code Playgroud)


Deb*_*anB 6

根据您的问题,因为剪贴板中已经有一些文本可以将其粘贴到文本字段中,您可以使用该方法,并且可以使用以下解决方案:getDefaultToolkit()

//required imports
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
//other lines of code
driver.findElement(By.id("copy_to_clip")).click(); //text copied to clipboard
String myText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor); // extracting the text that was copied to the clipboard
driver.findElement(By.name("to")).sendKeys(myText);//passing the extracted text to the text field
Run Code Online (Sandbox Code Playgroud)