简体   繁体   English

如何在不使用剪贴板或操作 CTRL+C、CTRL+V 的情况下将字符串中的“\\t”或“tab”发送到 selenium 中的文本框

[英]How to send “\t” or “tab” within a string into textbox in selenium without using Clipboard or Actions CTRL+C, CTRL+V

I have a string like this.我有一个这样的字符串。

String inputString="This\tis\ta\tString";
Webelement inputbox=inputBoxXpath;
inputbox.sendKeys(inputString);

The problem with code above is that it sends 'This' then \\t is considered a keypress TAB which then moves the focus to next element.上面代码的问题在于它发送 'This' 然后 \\t 被认为是一个按键 TAB,然后将焦点移动到下一个元素。

To avoid that I am using the Clipboard way and that works flawlessly as long as the app is in focus.为了避免我使用剪贴板的方式,只要应用程序处于焦点,它就可以完美地工作。

//Partial solution
StringSelection selection = new StringSelection(inputString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
inputbox.click()
send_keys("CTRL+V") // Paste the string in clipboard.

This method works however, when the program is running and I copy something else to Clipboard then the inputString gets replaced by the contents of Clipboard.但是,此方法有效,当程序运行并且我将其他内容复制到剪贴板时, inputString 将被剪贴板的内容替换。

This also causes issues if I want to run the code on a server VM如果我想在服务器 VM 上运行代码,这也会导致问题

I have also tried Actions to send the keys however the output is still faulty.我也尝试过Actions发送密钥,但是输出仍然有问题。

What I am looking for is a way to use native sendKeys('string') where string contains \\t and \\n, without using CTRL+C and CTRL+V or getCLipboard and setClipboard.我正在寻找的是一种使用原生 sendKeys('string') 的方法,其中 string 包含 \\t 和 \\n,而不使用 CTRL+C 和 CTRL+V 或 getCLipboard 和 setClipboard。

You can do it with javascript.你可以用javascript来做。 This allow you to set the value directly into the object.这允许您将值直接设置到对象中。

In Java you execute it like this:在 Java 中,您可以像这样执行它:

    @Test
    public void OptionClickTest() throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
        var driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.google.com");

        var object = driver.findElement(By.xpath("//input[@name='q']"));
        ((JavascriptExecutor) driver).executeScript("arguments[0].value='this\tis\tmy\ttext'", object);

}

It doesn't work on all types of input boxes - but it worked for me on google so it's worth a go:它不适用于所有类型的输入框 - 但它在谷歌上对我有用,所以值得一试:

谷歌字符串中的标签

将输入字符串中的 '\\t' 替换为 '\ '( Unicode 字符 'CHARACTER TABULATION' 的Java 编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM