如何使用Selenium WebDriver执行复制/粘贴

时间:2018-07-05 17:44:35

标签: java selenium testing selenium-webdriver

我想使用Java中的Selenium Webdriver将粘贴到已经存在于输入文本的本地变量中。 为此,我使用了这种方法:

public static void copyText(final String id, final String text) throws Exception {
        waitForJQueryProcessing(DRIVER, N_30);
        WebElement elem = DRIVER.findElement(By.id(id));
        DRIVER.findElement(By.id(id)).clear();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Clipboard clipboard = toolkit.getSystemClipboard();
        StringSelection strSel = new StringSelection(text);
        clipboard.setContents(strSel, null);
        elem.sendKeys(Keys.chord(Keys.CONTROL, "v", text));
        System.out.println(text);

    }

执行测试时,我会空白,不知道为什么?

2 个答案:

答案 0 :(得分:0)

尝试以下代码,并检查是否可以帮助您。

String CopyText = driver.findElement(By.xpath("your xpath to order id")).getText();
driver.findElement (By.xpath("/html/body/main/div/div/div[2]/div/div/div[2]/div/table/tbody
/tr[2]/td[2]")).sendKeys(myOrderText ));

或尝试以下代码:

// or any locator strategy that you find suitable 
        WebElement locOfOrder = driver.findElement(By.id("id of the element to be copied"));
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"));

答案 1 :(得分:0)

当您尝试将字符序列剪贴板复制到<input>元素时,可以使用以下解决方案:

//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
WebElement elem = DRIVER.findElement(By.id(id));
elem.clear();
String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
elem.sendKeys(data);