selenium clear() command doesn't clear the element - selenium

I have been writing selenium scripts for a while in Java. I encountered a very weird issue today. Here is the issue:
I cleared a text field using webelement.clear() method, later while executing next command (click event), the text area I had previously cleared, is now populated with previously filled value.
Here is the code snippet:
mobileNumField.get(0).clear();
Thread.sleep(4500);
emailAddress.get(0).click();
emailAddress.get(0).clear();
Thread.sleep(4500);
emailAddress.get(0).sendKeys(Keys.TAB);

I don't know the exact reason for your element keeping its value, but you can try an alternative text clearance by sending 'Ctrl+A+Delete' key combination using sendKeys method of the element's object:
emailAddress.sendKeys(Keys.chord(Keys.CONTROL,"a", Keys.DELETE));

It's possible that the fields you're trying to fill has autocomplete attribute set to on. [Reference]
If clear() works when the line executes then it's safe to say that this is not a webdriver specific issue.
It would help if you can show the html snippet of the page section you're working on.
Possible areas of debugging:
forcefully remove autocomplete attribute on page load using java script executor
turn off autocomplete setting on the driver level. I believe the solution would vary depending on the driver being used.
Good luck!
PS: Those Thread.sleep(s) are not advisable.

I solved it by adding a function to my BasePage to clear fields by a given WebElement.
public void clearWebField(WebElement element){
while(!element.getAttribute("value").equals("")){
element.sendKeys(Keys.BACK_SPACE);
}
}
You can also implement this method in the page that experiencing the problem.

I am using Mac and the following code helps also
public static void macCleanHack(WebElement element) {
String inputText = element.getAttribute("value");
if( inputText != null ) {
for(int i=0; i<inputText.length();i++) {
element.sendKeys(Keys.BACK_SPACE);
}
}
}

I had a similar issue with a text field that used an auto-complete plugin. I had to explicitly clear the attribute value as well as do a SendKeys. I created an extension method to encapsulate the behaviour, hopefully the snippet below will help:
public static void SendKeysAutocomplete(this IWebElement element, string fieldValue)
{
element.SendKeys(fieldValue);
element.SetAttribute("value", fieldValue);
}
public static void SetAttribute(this IWebElement element, string attributeName, string attributeValue)
{
var driver = WebDriverHelper.GetDriverFromScenarioContext();
var executor = (IJavaScriptExecutor)driver;
executor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, attributeName, attributeValue);
}

Faced a similar problem. The input field is cleared but the error message is not updated. It seems that some input fields work correctly only if you enter and delete a character:
element.sendKeys(text);
element.sendKeys(Keys.SPACE, Keys.BACK_SPACE);

Hope this helps to clear the field and then sendKeys() the needed value
while (!inputField.getAttribute("value").equals("")) {
inputField.sendKeys(Keys.BACK_SPACE);
}
inputField.sendKeys("your_value");

In some webforms clearing the field followed by .sendKeys() won't work because it keeps repopulating it with some autofill value (in my case it was due to an onfocus attribute function of an input element). Action chains didn't help, the only thing that worked for me was replacing the value attribute directly with javascript:
In Java:
driver.executeScript("document.getElementById('elementID').value='new value'");
In Python (nearly identical):
driver.execute_script("document.getElementById('elementID').value='new value'")
For more on the Java version of this solution see this question.

Related

How to delete data from fields in selenium

I have an issue that I am facing.
I have a text in the text box that I want to delete, the problem is that
driver.find_element_by_id('foo').clear()
not work and I need something harder than this clear function that do nothing.
I used this mthood that actually worked in windows:
element.sendKeys(Keys.CONTROL + "a");
element.sendKeys(Keys.DELETE);
if I want it to run on mac and on Linux machine, how can I perform it?
please the clear() not worked please do not provide solution with the clear() method
Use execute_script:
element=driver.find_element_by_id('foo');
driver.execute_script("arguments[0].value=' ';", element);
try
driver.findElement(yourelement).sendKeys("");
or variant
use Actions action = new Actions(driver);
// ... // may be move cursor to field
action.sendKeys(Keys.ARROW_LEFT);
action.build().perform();
may be problem in selenium library error, or in the webdriver version,
or conflict with js-framework on a form?
i use this also
public void clearAndInputStringData(By locator, String text) throws Exception {
ClickElementWhenClickable(locator);
WebElement element = getWebDriver().findElement(locator);
// element.sendKeys(Keys.CONTROL + "a");
Actions actions = new Actions(getWebDriver());
actions.doubleClick(element).perform();
element.sendKeys(Keys.DELETE);
element.sendKeys(text);
}

WebDriverEventListener and loggin sendKeys data

I have been using WebDriverEventListener to log various message and one of them is the data used by sendKeys method. API -org.openqa.selenium.support.events.WebDriverEventListener#beforeChangeValueOf can be used to log messages before keying in data in text field. But I get access to only element locator using WebElement argument. Is there a way to also access data which is keyed in to element?
Before change method you are providing element locator, so you get the value as you do for an input field. Implement the beforeChangeValueOf method as follows-
public void beforeChangeValueOf(WebElement element, WebDriver arg1) {
System.out.println("Before change: "+element.getAttribute("value"));
}
Use the method:
public void afterChangeValueOf(WebElement element,
WebDriver driver,
java.lang.CharSequence[] keysToSend);
keysToSend parameter will give you the keyed data.

Captcha in oracle adf project

I'm trying to use captcha as it's shown in this example:
http://www.oracle.com/technetwork/developer-tools/jdev/captcha-099103.html
And it works fine in .jspx page or in .jsff page fragment, but I have to place captcha onto the first page of taskflow, and there... it's not updated! /* I mean the button "can't read image" doesn't work */ I have no idea why. Can anybody help?
Actually, I figured out how to do it by myself:
we need captcha image binding in our bean and the resetting method:
private RichImage captchaImage;
public void setCaptchaImage(RichImage captchaImage) {
this.captchaImage = captchaImage;
}
public RichImage getCaptchaImage() {
return captchaImage;
}
public void resetCaptcha(ActionEvent actionEvent) {
captchaImage.setSource("/captchaservlet?rand=" +
String.valueOf(Math.random()));
AdfFacesContext.getCurrentInstance().addPartialTarget(captchaImage.getParent());
}
All, I didn't know how to do was adding parameter to "/captchaservlet"
And now it works fine :)
But the next problem appears: when returning to this page with captcha from the second one in task flow I need to refresh captcha image. Is there any method that is executed on page return or something?
Aaaaaaaaaaaand I found even more elegant solution: one should just set the source of the captcha image to this method using the expression builder:
public String getCaptchaSource() {
return "/captchaservlet?rand=" + String.valueOf(Math.random());
}
The button "Refresh", of course, should be set as a partial trigger for the image, as in the example.
And that's it :)

Websdriver - sendKeys command is not typing on Password type field

I am trying to learn selenium webdriver automation but I am finding that the sendKeys command is not typing on Password type fields. I can see that some other people are also experiencing the same problem by googling it, but I haven't seen any correct answer yet. Could anyone please help me here.
Please find below sample code; I generated code from Selenium IDE and its working fine on IDE but not when I use webdriver.
package com.example.tests;
public class Login {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.webs.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLogin() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.cssSelector("span")).click();
driver.findElement(By.id("FWloginUsername")).clear();
driver.findElement(By.id("FWloginUsername")).sendKeys("aug2qatestingqa#yahoo.com");
driver.findElement(By.id("FWloginPassword2")).clear();
driver.findElement(By.id("FWloginPassword2")).sendKeys("webs");
driver.findElement(By.id("sign_in_leaf")).click();
}
There were two password fields and one is hidden. Solution is to click on first password [hidden] field to get second password field enabled.
driver.findElement(By.id("FWloginUsername")).sendKeys("aug2qatestingqa#yahoo.com");
driver.findElement(By.id("FWloginPassword")).click();
driver.findElement(By.id("FWloginPassword2")).clear();
driver.findElement(By.id("FWloginPassword2")).sendKeys("webs");
I had almost a similar situation for Password field. There were two elements for the same 'Password' field but with different IDs. The JavaScript was toggling "type = password" on run time for a click, clear or any action to this field.
Solution in this case is to find the text with input type = password,
for example:
driver.FindElement(By.CssSelector("input[type='password']")).SendKeys(IWebElement);
My problem was that I used ActionChains which caused the later fields not being filled when using send_keys method.
The solution was to call actions.reset_actions()
e.g.
actions = ActionChains(driver)
actions.key_down(Keys.LEFT_CONTROL).send_keys("a").perform()
actions.key_down(Keys.LEFT_CONTROL).send_keys("c").perform()
actions.reset_actions()
# now send_keys() method works again
cvvTxtBox().sendKeys("1234");
cvvTxtBox().sendKeys(Keys.TAB);
Final Solution on this problem.
Else use Robot

How to use "isTrue" method of "Text" class?

I am unable to use "isTrue" method of text class
Here is the "Text" class detail
http://selenium.googlecode.com/git/docs/api/java/index.html
// Code i have written
public void researchSelenium(){
driver.get(baseUrl);
ConditionRunner.Context cont = new Research();
Text obj = new Text("Why implement a customer referral program?");
System.out.println(obj.isTrue(cont));
driver.close();
driver.quit();
I dont know what to do here
ConditionRunner.Context cont = new Research(); //After "new" what should i write?
object of ConditionRunner.Context will pass to "isTrue" method
I'm going to make a few presumptions here:
driver is a selenium web driver instance
You are trying to find if a text field is present in your web page
You know what the text is, but not its xpath (or at least do not care "where" it is).
In this case, you just have a minor syntaxical error
public void researchSelenium()
{
driver.get(baseUrl);
//Not sure what this is doing.
ConditionRunner.Context cont = new Research();
//Small chgange here
string obj = "Why implement a customer referral program?";
System.out.println(driver.isTextPresent(obj));
driver.close();
driver.quit();
}
NB. the above is "free coded" and I've not tested/complied it. Feel free to edit if there's a minor problem.
APPEND:
Personally I'd use NUnit to handle tests, so in that case I'd use:
Assert.isTrue(driver.isTextPresent(obj));
To test if that text was actually present, but how you're running your tests is not something that's stated in your question.