Selenium: How to enter white space as the value of a text field? - selenium

I have a form text field that is being populated with a default value. I would like to clear the value and enter white space to assert that the expected validation occurs. I am using Selenium RC and the PHPUnit Selenium extension. How can I achieve this?
Note: I have already tried doing these, but they do not work:
$this->type('FirstName', " "); //spaces
$this->type('FirstName', "\t"); //tab character
They clear the value from the field, but they do not enter the white space into the field.
Update: I found that if you are using Selenium IDE, you can type white space by using their ${space} variable but this does not work when using Selenium RC and the PHPUnit Selenium extension.

recently I am having the same problem just like Andrew where the ${space} isn't work in Selenium RC. I found out that Zugwalt's solution is useful. Here is what I did to capture the whitespace.
selenium.focus("txt_textbox1");
selenium.keyPressNative("32");
strOutput = selenium.getEval("this.browserbot.findElement('txt_textbox1').value = ' ';");
Hope this help ;)
THanks #!

I fixed this in the phpunit-selenium code on github and made a pull request to the maintainer.
Here is my gist if anyone cares:
https://github.com/undernewmanagement/phpunit-selenium/commit/1b783ba8cfe4736f525b316a75a991e0a701afd1

You could use javascript injection and manipulate the value directly
selenium.getEval("this.browserbot.findElement('FirstName').value = ' ';");
Note this will not fire off any events so you would have to manually trigger them if desired.

How about setting it's value to an empty string ('')?

How about using the keyPress() function to "press" the spacebar?

You can try selenium.typeKeys('FirstName'," ");
Please let me know if it worked.

This should work for phpunit with Selenium:
class MyTest extends PHPUnit_Extensions_Selenium2TestCase
{
public function testSomething()
{
$textField = $this->byCssSelector('.blah');
// ...
$textField->clear();
$textField->value(" ");
// test assertion to follow
}
}
If you want to enter a sentence, the following won't work:
$textField->value("this is a sentence.");
The following will:
$textField->value("this");
$textField->value(" ");
$textField->value("is");
$textField->value(" ");
$textField->value("a");
$textField->value(" ");
$textField->value("sentence.");

Related

instead of sendkeys last copied item from clipboard is getting entered in the element

In my application I have an email field and I'm using sendkeys to send an email address, but instead of sendkeys selenium inserts the value from clipboard. Do anyone faced this issue?
code:
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample#sample.com")
since Id is dynamic I have taken xpath from parent container
In Node.js javascript, on hungarian keyboard, the # sign in sendKeys has replaced with the content of clipboard. If you try to replace "#" width its unicode value "\u0040", the result is same, the sendKeys has has replaced with the content of clipboard, even though try to the tricky Key.chord( Key.ALT, "v", Key.NULL ) form, it does nothing.
// if clipboard contains XXX
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample#sample.com")
// result: field content is sampleXXXsample.com
If you put # sign on the clipboard, it works well, but you cant guarantee the content of clipboard in test automation. There is a way, to send keys to the active item.
I would avoid to fill the field with javascript, as mentioned above, because javascript fill it directly, does not care with the field status, fill it with value even though the field is inactive, do not triggers events, etc, javascript is brute force fill the field.
Send. Keys. There is a npm package for it. It is a wrapper for powershell sendkeys, so works only on windows.
npm install -g sendkeys
and the test code:
const sendkeys = require( 'sendkeys');
WebElement email=driver.findElement(By.xpath("//div[#class='auth-container']//input[#type='text']");
email.sendKeys("sample")
// result: cursor is in the field, field contains 'sample'
sendkeys.sync( "#sample.com" )
// result: field content is 'sample#sample.com'
If send keys is not working try using action chains. It is often a good way to solve selenium interaction problems.
from selenium.webdriver.common.action_chains import ActionChains
action = ActionChains(driver)
email = driver.find_element_by_xpath("//div[#class='auth-container']//input[#type='text']"))
action.send_keys_to_element(email, "sample#sample.com").perform()
hope this helps
I am run script in java, hope this help you..
Using javascript I successfully send data into textbox.
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('identifierId').value='admin'");
Another way :-
WebElement Username = driver.findElement(By.xpath("//*[#id=\"identifierId\"]"));
((JavascriptExecutor)driver).executeAsyncScript("arguments[0].value='admin'",Username);
Here we are passing WebElement as a argument to the javaScript.
For more information refer this link
Another way is using robot class ..Common solution is to use the clipboard, Copy text and paste that text into text field.
String username = "admin";
StringSelection stringSelection = new StringSelection(username);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
This doesn't type the entire "string" but helps to type whatever you want other than one character at a time.
String un="admin";
char c;
int l=un.length(),v1=0,v2=0;
//System.out.println(l);
while(v1<l)
{
c=un.charAt(v1);
v2=(int) c; //converts character to Unicode.
robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(v2));
Thread.sleep(150);
robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(v2));
v1++;
}
see it works perfectly and it's awesome! Though it doesn't work for special characters which cannot be traced by unicode like |,!...etc.
I have encountered this, but it seemed to be intermittent. The code that was working well for months, suddenly doing the same thing (pasting from clipboard in place of every # aka "at sign" ).
I was able to make it go away (won't say "fix") by updating Chromedriver. I suspect that this was because Chrome has auto-updated, but the Chromedriver didn't. Can't be sure, because also had to reboot in the process.
In any case, this is not "normal". Email addresses with # sign should be passed through sendKeys without problems.
This works for me:
chromeoptions.AddUserProfilePreference("settings.language.current_input_method", "US");

selenium ide having problems with dynamic id

i am testing our web based application using selenium. I am having problem in a button which has dynamic id and the class is similar to the last html page so i am unable to go ahead with the testing. below is the source of the button
input id="aui_3_4_0_1_554" class="addto_cart_button" type="button" onclick="chkMaxRequestPerDay();" value="Request Quote">
I want to know how can i tell selenium ide to check with value so that it can proceed
Thanks
you can try using xpath with value,
//input[#value='Request Quote']
or
//input[#value='Request Quote' and #class='addto_cart_button']
I think something like below should also work
//input[contains(#id, 'aui_')]
or
//input[#class='addto_cart_button']
this will give you a List
loop through them and in the loop check
loop over List<Webelement> {
if( webelement.getAttribute("onclick").indexOf("chkMaxRequestPerDay") != -1) {
// here is the element. do what ever you want
}
}

Selenium SendKeys not working for open brackets and harsh keys when using java

I have using selenium webdriver 2.33.0 and i have a requirement of sending data with the following characters inside the data ("(", "#")
When we tried to send these characters using sendkeys
"WebElement dat = driver.findElement(By.xpath("xpathexpression);
dat.sendkeys("select * from (?s, ?p, ?o)");
The following data gets displayed in the textarea as select * from ?s, ?p, ?o)
the open bracket is missing. I have used selenium actions class sendkeys and robot sendkeys also.
I am not able to fix the issue. Can someone help me on this?
Ugly but efficient workaround: replace the opening brackets ( with the key sequence shift + 9, as suggested by user2935099.
dat.sendKeys(Keys.chord(Keys.SHIFT, "9"));
Funnily, this seems to work regardless of your current keyboard layout (I use an Irish locale with a French layout).
I stumbled upon this one with version 2.40.0, and it is definitely a bug in Selenium. Using the following in the Firefox JavaScript console works flawlessly:
var box = getElementById('SearchBox');
box.setValue('AB (CDE FGH)');
The issue is resolved when using actions class
WebElement dat = driver.findElement(By.xpath("xpathexpression");
dat.click();
Actions data = new Actions(driver);
data.sendKeys(Keys.chord(Keys.CONTROL,"a"),Keys.DELETE);
data.perform();
query = query.replaceAll("\\(", Keys.chord(Keys.SHIFT,"9"));
query = query.replaceAll("\\#", Keys.chord(Keys.SHIFT,"3"));
query = query.replaceAll("\\-", Keys.SUBTRACT.toString());
query = query.replaceAll("\\}", Keys.chord(Keys.SHIFT,"]"));
data.sendKeys(query);
data.perform();
I tried entering the same thing with my selenium setup and it worked fine in both firefox and chrome. I am not not very sure about the reason but one thing that I can notice that you are using very old selenium version(2.33.0) currently 2.37.0 is available. May be you should try updating the selenium and t should work as expected.
Same problem here, using 2.40.0 my workaorund was using clipboard, not pretty but testsystems have not much use for a clipboard anyway...
public static void setTextByClipboard(WebElement element, String text) {
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
element.sendKeys(Keys.chord(Keys.CONTROL, "v"));
}

reading text from textarea in webdriver

I am trying to read text from textarea when writing a webdriver test in Java. For some reason I am getting null back when I use .getAttribute():
WebElement text = wd.findElement(By.id("edit-pi-sample-geo-id"));
String textagain = text.getAttribute("aaaa");
How do I fix this?
I got this working. Here is the solution-
WebElement text = wd.findElement(By.id("edit-pi-analytics-tms-id"));
String textagain = text.getAttribute("value");
I was using the actual value in the textarea in the previous code example i posted which was kinda silly. Thanks guys for your help
I'm using selenium version 3.4 and using element.getAttribute("value") that work for me. The element.getText() would return empty value for TextArea.
So finding an element returns a web element. To get the text of the element you have to call getText(), so from above
WebElement element = wd.findElement(By.id("edit-pi-sample-geo-id"));
String text = element.getText()

Selenium and ckEditor

Does anybody know How I can get the ckEdtior to work with Selenium.
I'm not able to get the focus to the "html edit" field or change the value of the html field.
Does anybody has experience with this ?
Just for completing the anwser:
I got it to work with:
runScript("CKEDITOR.instances['InstanceName'].setData('<p>testContent</p>');")
It did not work with the getEval command.
When I have had a to test against WYSIWYG editors I have had to build my own mechanism to work in the content area. Normally it involves having to set the inner HTML of object and then start using the page manipulators in the tool bars.
With Selenium 2 you will be able to send keystrokes in so that they work better and a lot easier.
Working in Selenium:
selenium.runScript("for(var i in CKEDITOR.instances) { var x = CKEDITOR.instances[i]; " + " x.setData('" + texto + "'); }");
I've found a solution that worked for me. You can insert a user-extension.js (Options > options > Selenium Core Extension > Browse ) writing the following:
Selenium.prototype.doInsertCKEditor = function(locator,word)
{
this.doWaitForCondition("var x = Selenium.browserbot.findElementOrNull('//td[#id=\"cke_contents_form \"]');x != null;", "50000");
this.doRunScript("CKEDITOR.instances['"+locator+"'].setData('"+word
+"');");
}
This will add the insertCKEditor option in the Command options of Selenium IDE.