Performing a copy and paste with Selenium 2 - selenium

Is there any way to perform a copy and paste using Selenium 2 and the Python bindings?
I've highlighted the element I want to copy and then I perform the following actions
copyActionChain.key_down(Keys.COMMAND).send_keys('C').key_up(Keys.COMMAND)
However, the highlighted text isn't copied.

To do this on a Mac and on PC, you can use these alternate keyboard shortcuts for cut, copy and paste. Note that some of them aren't available on a physical Mac keyboard, but work because of legacy keyboard shortcuts.
Alternate keyboard shortcuts for cut, copy and paste on a Mac
Cut => control+delete, or control+K
Copy => control+insert
Paste => shift+insert, or control+Y
If this doesn't work, use Keys.META instead, which is the official key that replaces the command ⌘ key
source: https://w3c.github.io/uievents/#keyboardevent
Here is a fully functional example:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Safari(executable_path = '/usr/bin/safaridriver')
browser.get("http://www.python.org")
elem = browser.find_element_by_name("q")
elem.clear()
actions = ActionChains(browser)
actions.move_to_element(elem)
actions.click(elem) #select the element where to paste text
actions.key_down(Keys.META)
actions.send_keys('v')
actions.key_up(Keys.META)
actions.perform()
So in Selenium (Ruby), this would be roughly something like this to select the text in an element, and then copy it to the clipboard.
# double click the element to select all it's text
element.double_click
# copy the selected text to the clipboard using CTRL+INSERT
element.send_keys(:control, :insert)

Pretty simple actually:
from selenium.webdriver.common.keys import Keys
elem = find_element_by_name("our_element")
elem.send_keys("bar")
elem.send_keys(Keys.CONTROL, 'a') # highlight all in box
elem.send_keys(Keys.CONTROL, 'c') # copy
elem.send_keys(Keys.CONTROL, 'v') # paste
I imagine this could probably be extended to other commands as well.

Rather than using the actual keyboard shortcut i would make the webdriver get the text. You can do this by finding the inner text of the element.
WebElement element1 = wd.findElement(By.locatorType(locator));
String text = element1.getText();
This way your test project can actually access the text. This is beneficial for logging purposes, or maybe just to make sure the text says what you want it to say.
from here you can manipulate the element's text as one string so you have full control of what you enter into the element that you're pasting into. Now just
element2.clear();
element2.sendKeys(text);
where element2 is the element to paste the text into

elem.send_keys(Keys.SHIFT, Keys.INSERT)
It works FINE on macOS Catalina when you try to paste something.

I cannot try this on OSX at the moment, but it definitely works on FF and Ubuntu:
import os
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
with open('test.html', 'w') as fp:
fp.write("""\
<html>
<body>
<form>
<input type="text" name="intext" value="ABC">
<br>
<input type="text" name="outtext">
</form>
</body>
</html>
""")
driver = webdriver.Firefox()
driver.get('file:///{}/test.html'.format(os.getcwd()))
element1 = driver.find_element_by_name('intext')
element2 = driver.find_element_by_name('outtext')
time.sleep(1)
element1.send_keys(Keys.CONTROL, 'a')
time.sleep(1)
element1.send_keys(Keys.CONTROL, 'c')
time.sleep(1)
element2.send_keys(Keys.CONTROL, 'v')
The sleep() statements are just there to be able to see the steps, they are of course not necessary for the program to function.
The ActionChain send_key just switches to the selected element and does a send_keys on it.

The solutions involving sending keys do not work in headless mode. This is because the clipboard is a feature of the host OS and that is not available when running headless.
However all is not lost because you can simulate a paste event in JavaScript and run it in the page with execute_script.
const text = 'pasted text';
const dataTransfer = new DataTransfer();
dataTransfer.setData('text', text);
const event = new ClipboardEvent('paste', {
clipboardData: dataTransfer,
bubbles: true
});
const element = document.querySelector('input');
element.dispatchEvent(event)

Solution for both Linux and MacOS (for Chrome driver, not tested on FF)
The answer from #BradParks almost worked for me for MacOS, except for the copy/cut part. So, after some research I came up with a solution that works on both Linux and MacOS (code is in ruby).
It's a bit dirty, as it uses the same input to pre-paste the text, which can have some side-effects. If it was a problem for me, I'd try using different input, possibly creating one with execute_script.
def paste_into_input(input_selector, value)
input = find(input_selector)
# set input value skipping onChange callbacks
execute_script('arguments[0].focus(); arguments[0].value = arguments[1]', input, value)
value.size.times do
# select the text using shift + left arrow
input.send_keys [:shift, :left]
end
execute_script('document.execCommand("copy")') # copy on mac
input.send_keys [:control, 'c'] # copy on linux
input.send_keys [:shift, :insert] # paste on mac and linux
end

If you want to copy a cell text from the table and paste in search box,
Actions Class : For handling keyboard and mouse events selenium provided Actions Class
///
/// This Function is used to double click and select a cell text , then its used ctrl+c
/// then click on search box then ctrl+v also verify
/// </summary>
/// <param name="text"></param>
public void SelectAndCopyPasteCellText(string text)
{
var cellText = driver.FindElement(By.Id("CellTextID"));
if (cellText!= null)
{
Actions action = new Actions(driver);
action.MoveToElement(cellText).DoubleClick().Perform(); // used for Double click and select the text
action = new Actions(driver);
action.KeyDown(Keys.Control);
action.SendKeys("c");
action.KeyUp(Keys.Control);
action.Build().Perform(); // copy is performed
var searchBox = driver.FindElement(By.Id("SearchBoxID"));
searchBox.Click(); // clicked on search box
action = new Actions(driver);
action.KeyDown(Keys.Control);
action.SendKeys("v");
action.KeyUp(Keys.Control);
action.Build().Perform(); // paste is performed
var value = searchBox.GetAttribute("value"); // fetch the value search box
Assert.AreEqual(text, value, "Selection and copy paste is not working");
}
}
KeyDown(): This method simulates a keyboard action when a specific keyboard key needs to press.
KeyUp(): The keyboard key which presses using the KeyDown() method, doesn’t get released automatically, so keyUp() method is used to release the key explicitly.
SendKeys(): This method sends a series of keystrokes to a given web element.

If you are using Serenity Framework then use following snippet:
withAction().moveToElement(yourWebElement.doubleClick().perform();
withAction().keyDown(Keys.CONTROL).sendKeys("a");
withAction().keyUp(Keys.CONTROL);
withAction().build().perform();
withAction().keyDown(Keys.CONTROL).sendKeys("c");
withAction().keyUp(Keys.CONTROL);
withAction().build().perform();
withAction().keyDown(Keys.CONTROL).sendKeys("v");
withAction().keyUp(Keys.CONTROL);
withAction().build().perform();
String value = yourWebElement.getAttribute("value");
System.out.println("Value copied: "+value);
Then send this value wherever you want to send:
destinationWebElement.sendKeys(value);

Related

Locating elements in section with selenium

I'm trying to enter text into a field (the subject field in the image) in a section using Selenium .
I've tried locating by Xpath , ID and a few others but it looks like maybe I need to switch context to the section. I've tried the following, errors are in comments after lines.
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
opts = Options()
browser = Firefox(options=opts)
browser.get('https://www.linkedin.com/feed/')
sign_in = '/html/body/div[1]/main/p/a'
browser.find_element_by_xpath(sign_in).click()
email = '//*[#id="username"]'
browser.find_element_by_xpath(email).send_keys(my_email)
pword = '//*[#id="password"]'
browser.find_element_by_xpath(pword).send_keys(my_pword)
signin = '/html/body/div/main/div[2]/div[1]/form/div[3]/button'
browser.find_element_by_xpath(signin).click()
search = '/html/body/div[8]/header/div[2]/div/div/div[1]/div[2]/input'
name = 'John McCain'
browser.find_element_by_xpath(search).send_keys(name+"\n")#click()
#click on first result
first_result = '/html/body/div[8]/div[3]/div/div[1]/div/div[1]/main/div/div/div[1]/div/div/div/div[2]/div[1]/div[1]/span/div/span[1]/span/a/span/span[1]'
browser.find_element_by_xpath(first_result).click()
#hit message button
msg_btn = '/html/body/div[8]/div[3]/div/div/div/div/div[2]/div/div/main/div/div[1]/section/div[2]/div[1]/div[2]/div/div/div[2]/a'
browser.find_element_by_xpath(msg_btn).click()
sleep(10)
## find subject box in section
section_class = '/html/body/div[3]/section'
browser.find_element_by_xpath(section_class) # no such element
browser.switch_to().frame('/html/body/div[3]/section') # no such frame
subject = '//*[#id="compose-form-subject-ember156"]'
browser.find_element_by_xpath(subject).click() # no such element
compose_class = 'compose-form__subject-field'
browser.find_element_by_class_name(compose_class) # no such class
id = 'compose-form-subject-ember156'
browser.find_element_by_id(id) # no such element
css_selector= 'compose-form-subject-ember156'
browser.find_element_by_css_selector(css_selector) # no such element
wind = '//*[#id="artdeco-hoverable-outlet__message-overlay"]
browser.find_element_by_xpath(wind) #no such element
A figure showing the developer info for the text box in question is attached.
How do I locate the text box and send keys to it? I'm new to selenium but have gotten thru login and basic navigation to this point.
I've put the page source (as seen by the Selenium browser object at this point) here.
The page source (as seen when I click in the browser window and hit 'copy page source') is here .
Despite the window in focus being the one I wanted it seems like the browser object saw things differently . Using
window_after = browser.window_handles[1]
browser.switch_to_window(window_after)
allowed me to find the element using an Xpath.

Unable to handle disabled element using selenium when there is no disabled attribute present

I have tried using isEnabled() but because its not a button and there is no disabled attribute present it always returns me true.
I have pasted code by inspecting, Please help me out in this,
9:29 AM
Click on this to see the code
It seems like your class name update with the "disabled" text when its disabled. So you can try bellow method.
<<<<<<<<Imports>>>>>>>>
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
<<<<<<<<Code>>>>>>>>
//get class value of the element
attribute = WebUI.getAttribute(findTestObject('<<Element Locator>>'), 'class')
boolean isSubstringPresent(String subString, String fullString) {
return fullString.contains(subString)
}
//this will print true if the disabled text included in the class
println isSubstringPresent("disabled", attribute) // true
Mostly you can return correct boolean from above print. If it works use IF condition and plan your work.
If the above method not works I would like to suggest to run bellow Javascript in your browser and check its output.
document.getElementByClassName("sc-AxhUy irOhyl bigtix-session bigtix-session--available bigtix-session--disabled").disabled
If it works you can execute the same in your automation, however I'm not familiar with Katalon Studio and found that following code will work for you.
<<<<<<<<Imports>>>>>>>>
import org.openqa.selenium.WebDriver as WebDriver
import org.openqa.selenium.JavascriptExecutor as JavascriptExecutor
import com.kms.katalon.core.webui.driver.DriverFactory as DriverFactory
<<<<<<<<Code>>>>>>>>
WebDriver driver = DriverFactory.getWebDriver()
JavascriptExecutor js = ((driver) as JavascriptExecutor)
String disabledState = js.executeScript(‘sc-AxhUy irOhyl bigtix-session bigtix-session--available bigtix-session--disabled").disabled’)
print(disabledState)
As I can see in your attached image, there is one attribute aria-disabled = true, You can always check against that attribute for checking whether it is enabled or disabled.

Not able to Enter Text in a TextBox using Selenium Webdriver

I have a TextBox that appears on Radio Button Selection and I have to enter values in a particular format(XYZ989898-99). However I am unable to do so by using the commonly used methods of entering text in selenium.
Background info related to Textbox :
TextBox appears when user clicks on Yes radio button.
TextBox has default value as XYZ already entered.
SendKeys do not concatenate the text given without XYZ as well.
TextBox is inside an Iframe to which focus is shifted correctly.
The code does not fail, it just remained clicked on textbox without entering anything.
Approach 1 :
driver.findElement(locator).SendKeys("989898-99");
Approach 2 :
driver.findElement(locator).clear();
driver.findElement(locator).SendKeys("XYZ989898-99");
Approach 3 :
WebElement element = driver.findElement(locator);
Actions action1 = new Actions(driver);
action1.movetoElement(element).click().perform();
action1.sendKeys("XYZ989898-99");
HTML Sample :
<div class="value" ng-show="selectedValue" style="">
<label class="labelAboveTextBox">XYZ Number*</label>
<input type="text" class="Value" ng-model="XYZNumber" ng-
req="XYZNumber" xyz-input="" maxlength="12" style="value"
id="value" value="XYZ" required="required">
<!-- ngIf: invalidtspmessage -->
<span style="font-family: 'NeueHaasGroteskText';font-size:
0.7rem;color: black;">
Note: Enter XYZ is this format: XXXXXXXXX-XX
</span>
</div>
I would like to know If there is any other approach that can be used to get this problem resolved and also why does the above approaches failed to work.
You have used the wrong methods for sending the keys. (in approach 1 and 2)
Instead of .SendKeys(), you have to use .sendKeys() method for writing anything on UI side
Into the third approach, you have used the wrong method .movetoElement(). The method name is .moveToElement().
For sendKeys() don't need to use Actions class. basically, it is for Keyboard events and for mouse events.
(WebElement).sendKeys("989898-99"); // first approach you can use
(WebElement).clear(); // second approach you can use
(WebElement).sendKeys("XYZ989898-99");
Hope this will help you to solve your errors.
Other way you can use is to set the text is by using the JavaScriptExecutor. Give some delay before performing the action.
Try the below sample code :
Thread.sleep(3000);
((JavascriptExecutor) driver).executeScript("document.getElementById('value').value='XYZ989898-99';");
As the id is unique, you can use the JavaScript's getElementById() function to set the value.
If you want to set the text through the sendKeys() method and before that if you want to clear the text then simple clear() may not work instead you can try to delete the XYZ values first and try to send the values like below again :
// Wait for some time
Thread.sleep(3000);
// Locate the element first and store it in some variable
WebElement element = driver.findElement(By.id("value"));
// Fetch the existing text from the field first
String existingValue = element.getAttribute("value");
// Wait for some time
Thread.sleep(3000);
// Click on that element first so the focus will shift to there
element.click();
// Wait for some time
Thread.sleep(2000);
// Loop until the existing value length
for(int i=0;i<existingValue.length();i++) {
// Remove the existing character text one by one
element.sendKeys(Keys.BACK_SPACE);
}
// Try to send the text at the end, make sure that you should append XYZ as a prefix
element.sendKeys("XYZ989898-99");
I hope it helps...

First character is missing inconstantly while sending string to the ExtJS input via sendKeys()

I randomly face the issue of missing first character in the ExtJS5 input field, while sending string via sendKeys method.
System info:
Ubuntu 14.04 -> docker containers with selenium grid (2.48.2)
Browser Firefox
Code is simple. I just get input web element, wait if it's clickable (i.e. isEnabled and isDisplayed), clear and send string:
wait.until(ExpectedConditions.elementToBeClickable(input)).clear();
input.sendKeys(value);
input element is simple too:
<input id="textfield-1455-inputEl" data-ref="inputEl" type="text" role="textbox" size="1" name="name" class="x-form-field x-form-required-field x-form-text x-form-text-default x-form-focus x-field-form-focus x-field-default-form-focus" autocomplete="off" componentid="textfield-1455"/>
I've noticed that issue occurs only for the first sendKeys() executing on the page:
Enter the page, wait for page load, work with first input
Enter the page, wait for page load, choose Enable into corresponding select box in order to enable input field, work with input field (image with this example is attached)
Enter the page, wait for page load, click button add in order to add the needed input field, work with input field
Other occurrences of the sendKeys on the page are stable.
I've looked for similar questions. It does not seem the issue with special characters (Missing characters example: 46-> 6; coverTest -> overTest; 1 -> nothing);
Also, I don't think it's an issue with missing characters due to remote webdriver infrastructure. The tests fail randomly but in exact places.
I know that I can use sendKeys(), then check the value of the input and repeat the sending action. However, it's the last option.
Is there any additional check needed for ExtJS input (any attribute in DOM) in order to be sure that input field is ready?
Appreciate your help.
Some times it happens with me. Try clicking on to the field first, but it's a wild guess assuming there can be some focus related issues.
Your sequence could be somewhat like this:
wait.until(ExpectedConditions.elementToBeClickable(input)).click();
input.clear();
input.sendKeys(value);
Weird thing is that I actually faced a situation, where I clicked it twice before sending values and it worked somehow :P
Another thing to try could be using a non-native javascript executor.
JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
myExecutor.executeScript("arguments[0].value='6';", input);
Sorry man, if the system would have been in front of me I'd have tried much more things.
I was struggling with sendKeys failing my self, but the following works pretty consistently. The method findVisibleElement is a custom wrapper for driver.until....
protected static boolean sendKeysByChar(By by, String input)
{
WebElement field = driver.findVisibleElement(by).base();
field.click();
field.clear();
for (int i = 0; i < input.length(); i++) {
String current = driver.findElement(by).getAttribute("value");
String nextChar = String.valueOf(input.charAt(i));
while (current.length() <= i || !current.endsWith(nextChar)) {
field.sendKeys(nextChar);
current = driver.findElement(by).getAttribute("value");
}
}
field = driver.findElement(by); // Refresh element
if (field.getAttribute("value").equals(input)) { return true; }
log.warn("Send keys by char failed.");
return false;
}

Typing the Enter/Return key in Selenium

I'm looking for a quick way to type the Enter or Return key in Selenium.
Unfortunately, the form I'm trying to test (not my own code, so I can't modify) doesn't have a Submit button. When working with it manually, I just type Enter or Return. How can I do that with the Selenium type command as there is no button to click?
import org.openqa.selenium.Keys
WebElement.sendKeys(Keys.RETURN);
The import statement is for Java. For other languages, it is maybe different. For example, in Python it is from selenium.webdriver.common.keys import Keys
Java
driver.findElement(By.id("Value")).sendKeys(Keys.RETURN);
OR,
driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);
Python
from selenium.webdriver.common.keys import Keys
driver.find_element_by_name("Value").send_keys(Keys.RETURN)
OR,
driver.find_element_by_name("Value").send_keys(Keys.ENTER)
OR,
element = driver.find_element_by_id("Value")
element.send_keys("keysToSend")
element.submit()
Ruby
element = #driver.find_element(:name, "value")
element.send_keys "keysToSend"
element.submit
OR,
element = #driver.find_element(:name, "value")
element.send_keys "keysToSend"
element.send_keys:return
OR,
#driver.action.send_keys(:enter).perform
#driver.action.send_keys(:return).perform
C#
driver.FindElement(By.Id("Value")).SendKeys(Keys.Return);
OR,
driver.FindElement(By.Id("Value")).SendKeys(Keys.Enter);
You can use either of Keys.ENTER or Keys.RETURN. Here are the details:
Usage:
Java:
Using Keys.ENTER:
import org.openqa.selenium.Keys;
driver.findElement(By.id("element_id")).sendKeys(Keys.ENTER);
Using Keys.RETURN:
import org.openqa.selenium.Keys;
driver.findElement(By.id("element_id")).sendKeys(Keys.RETURN);
Python:
Using Keys.ENTER:
from selenium.webdriver.common.keys import Keys
driver.find_element_by_id("element_id").send_keys(Keys.ENTER)
Using Keys.RETURN:
from selenium.webdriver.common.keys import Keys
driver.find_element_by_id("element_id").send_keys(Keys.RETURN)
Keys.ENTER and Keys.RETURN both are from org.openqa.selenium.Keys, which extends java.lang.Enum<Keys> and implements java.lang.CharSequence.
Enum Keys
Enum Keys is the representations of pressable keys that aren't text. These are stored in the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF.
Key Codes:
The special keys codes for them are as follows:
RETURN = u'\ue006'
ENTER = u'\ue007'
The implementation of all the Enum Keys are handled the same way.
Hence these is No Functional or Operational difference while working with either sendKeys(Keys.ENTER); or WebElement.sendKeys(Keys.RETURN); through Selenium.
Enter Key and Return Key
On computer keyboards, the Enter (or the Return on Mac OS X) in most cases causes a command line, window form, or dialog box to operate its default function. This is typically to finish an "entry" and begin the desired process and is usually an alternative to pressing an OK button.
The Return is often also referred as the Enter and they usually perform identical functions; however in some particular applications (mainly page layout) Return operates specifically like the Carriage Return key from which it originates. In contrast, the Enter is commonly labelled with its name in plain text on generic PC keyboards.
References
Enter Key
Carriage Return
Now that Selenium 2 has been released, it's a bit easier to send an Enter key, since you can do it with the send_keys method of the selenium.webdriver.remote.webelement.WebElement class (this example code is in Python, but the same method exists in Java):
>>> from selenium import webdriver
>>> wd = webdriver.Firefox()
>>> wd.get("http://localhost/example/page")
>>> textbox = wd.find_element_by_css_selector("input")
>>> textbox.send_keys("Hello World\n")
In Python
Step 1. from selenium.webdriver.common.keys import Keys
Step 2. driver.find_element_by_name("").send_keys(Keys.ENTER)
Note: you have to write Keys.ENTER
When writing HTML tests, the ENTER key is available as ${KEY_ENTER}.
You can use it with sendKeys, here is an example:
sendKeys | id=search | ${KEY_ENTER}
selenium.keyPress("css=input.tagit-input.ui-autocomplete-input", "13");
You just do this:
final private WebElement input = driver.findElement(By.id("myId"));
input.clear();
input.sendKeys(value); // The value we want to set to input
input.sendKeys(Keys.RETURN);
For those folks who are using WebDriverJS Keys.RETURN would be referenced as
webdriver.Key.RETURN
A more complete example as a reference might be helpful too:
var pressEnterToSend = function () {
var deferred = webdriver.promise.defer();
webdriver.findElement(webdriver.By.id('id-of-input-element')).then(function (element) {
element.sendKeys(webdriver.Key.RETURN);
deferred.resolve();
});
return deferred.promise;
};
driver.findElement(By.id("Value")).sendKeys(Keys.RETURN); or driver.findElement(By.id("Value")).sendKeys(Keys.ENTER);
For Selenium Remote Control with Java:
selenium.keyPress("elementID", "\13");
For Selenium WebDriver (a.k.a. Selenium 2) with Java:
driver.findElement(By.id("elementID")).sendKeys(Keys.ENTER);
Or,
driver.findElement(By.id("elementID")).sendKeys(Keys.RETURN);
Another way to press Enter in WebDriver is by using the Actions class:
Actions action = new Actions(driver);
action.sendKeys(driver.findElement(By.id("elementID")), Keys.ENTER).build().perform();
search = browser.find_element_by_xpath("//*[#type='text']")
search.send_keys(u'\ue007')
#ENTER = u'\ue007'
Refer to Selenium's documentation 'Special Keys'.
I just like to note that I needed this for my Cucumber tests and found out that if you like to simulate pressing the enter/return key, you need to send the :return value and not the :enter value (see the values described here)
Try to use an XPath expression for searching the element and then, the following code works:
driver.findElement(By.xpath(".//*[#id='txtFilterContentUnit']")).sendKeys(Keys.ENTER);
You can call submit() on the element object in which you entered your text.
Alternatively, you can specifically send the Enter key to it as shown in this Python snippet:
from selenium.webdriver.common.keys import Keys
element.send_keys(Keys.ENTER) # 'element' is the WebElement object corresponding to the input field on the page
If you are looking for "how to press the Enter key from the keyboard in Selenium WebDriver (Java)",then below code will definitely help you.
// Assign a keyboard object
Keyboard keyboard = ((HasInputDevices) driver).getKeyboard();
// Enter a key
keyboard.pressKey(Keys.ENTER);
To enter keys using Selenium, first you need to import the following library:
import org.openqa.selenium.Keys
then add this code where you want to enter the key
WebElement.sendKeys(Keys.RETURN);
You can replace RETURN with any key from the list according to your requirement.
There are the following ways of pressing keys - C#:
Driver.FindElement(By.Id("Value")).SendKeys(Keys.Return);
OR
OpenQA.Selenium.Interactions.Actions action = new OpenQA.Selenium.Interactions.Actions(Driver);
action.SendKeys(OpenQA.Selenium.Keys.Escape);
OR
IWebElement body = GlobalDriver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Escape);
object.sendKeys("your message", Keys.ENTER);
It works.
When you don't want to search any locator, you can use the Robot class. For example,
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
If you just want to press the Enter key (python):
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
action = ActionChains(driver)
action.send_keys(Keys.ENTER)
action.perform()
Actions action = new Actions(driver);
action.sendKeys(Keys.RETURN);
For Ruby:
driver.find_element(:id, "XYZ").send_keys:return
For Selenium WebDriver using XPath (if the key is visible):
driver.findElement(By.xpath("xpath of text field")).sendKeys(Keys.ENTER);
or,
driver.findElement(By.xpath("xpath of text field")).sendKeys(Keys.RETURN);
I had to send the Enter key in the middle of a text. So I passed the following text to send keys function to achieve 1\n2\n3:
1\N{U+E007}2\N{U+E007}3
Java/JavaScript:
You could probably do it this way also, non-natively:
public void triggerButtonOnEnterKeyInTextField(String textFieldId, String clickableButId)
{
((JavascriptExecutor) driver).executeScript(
" elementId = arguments[0];
buttonId = arguments[1];
document.getElementById(elementId)
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
document.getElementById(buttonId).click();
}
});",
textFieldId,
clickableButId);
}
It could be achieved using Action interface as well. In case of WebDriver -
WebElement username = driver.findElement(By.name("q"));
username.sendKeys(searchKey);
Actions action = new Actions(driver);
action.sendKeys(Keys.RETURN);
action.perform();
You can try:
selenium.keyPress("id="", "\\13");
If you are in this specific situation:
a) want to just press the key, but you not have a specific webElement to click on
b) you are using Selenium 2 (WebDriver)
Then the solution is:
Actions builder = new Actions(webDriverInstance);
builder.sendKeys(Keys.RETURN).perform();
For everyone using JavaScript / Node.js, this worked for me:
driver.findElement(By.xpath('xpath')).sendKeys('ENTER');