Missing the first letter on input field while using Selenium Webdriver (Java) - selenium-webdriver

I need to fill out the phone number field (with a placeholder = "(__) -") using Selenium WebDriver. The issue I'm facing is: the driver does it very quickly and the first number is missing in 40% of my tests. I mean the number is 965-234-43 and what the driver does is 652 - 34 - 43_.
My code is:
private void setBankPhone(String bankPhone) {
driver.findElement(bankPhoneField).click();
driver.findElement(bankPhoneField).clear();
driver.findElement(bankPhoneField).sendKeys(Keys.HOME + bankPhone);
checkBankPhone(bankPhone);
}
private void checkBankPhone(String bankPhone){
WebElement phonElement = driver.findElement(bankPhoneField);
if (!phonElement.getAttribute("value").equals(bankPhone)) {
setBankPhone(bankPhone);
}
}
With driver.findElement(bankPhoneField).sendKeys(bankPhone); it's impossible to fill out the field at all.

Though your code looks fine to me, I believe it's a latency/sync issue.
Can you try any of the below approaches before entering text to make sure readiness of the element?
1. Wait for JavaScript to load
WebDriverWait wait = new WebDriverWait(driver, timeOut);
JavascriptExecutor js_Executor = (JavascriptExecutor) getDriver();
ExpectedCondition<Boolean> jsLoad = driver -> js_Executor.executeScript("return document.readyState").toString().equals("complete");
ExpectedCondition<Boolean> jQueryLoad = driver -> js_Executor.executeScript("return jQuery.active").toString().equals("0");
// Wait for JavaScript and jQuery to be loaded.
wait.until(jsLoad);
wait.until(jQueryLoad);
2. Use wait conditions
WebDriverWait wait = new WebDriverWait(driver, timeOut);
wait.until(ExpectedConditions.elementToBeClickable(webElement));

Related

Element ... is not clickable at point (35, 37) [duplicate]

I am trying to make some tests using selenium based Katalon Studio. In one of my tests I have to write inside a textarea. The problem is that I get the following error:
...Element MyElement is not clickable at point (x, y)... Other element would receive the click...
In fact my element is place inside some other diva that might hide it but how can I make the click event hit my textarea?
Element ... is not clickable at point (x, y). Other element would receive the click" can be caused for different factors. You can address them by either of the following procedures:
Element not getting clicked due to JavaScript or AJAX calls present
Try to use Actions Class:
WebElement element = driver.findElement(By.id("id1"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
Element not getting clicked as it is not within Viewport
Try to use JavascriptExecutor to bring the element within Viewport:
JavascriptExecutor jse1 = (JavascriptExecutor)driver;
jse1.executeScript("scroll(250, 0)"); // if the element is on top.
jse1.executeScript("scroll(0, 250)"); // if the element is at bottom.
Or
WebElement myelement = driver.findElement(By.id("id1"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
The page is getting refreshed before the element gets clickable.
In this case induce some wait.
Element is present in the DOM but not clickable.
In this case add some ExplicitWait for the element to be clickable.
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("id1")));
Element is present but having temporary Overlay.
In this case induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.
WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
Element is present but having permanent Overlay.
Use JavascriptExecutor to send the click directly on the element.
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
I assume, you've checked already that there is no any other component overlapping here (transparent advertisement-iframes or some other component of the DOM => seen quite often such things in input/textfield elements) and, when manually (slowly) stepping your code, it's working smoothly, then ajax calls might cause this behaviour.
To avoid thread.sleep, try sticking with EventFiringWebDriver and register a handle to it.
(Depending on your application's techstack you may work it for Angular, JQuery or wicket in the handler, thus requiring different implementations)
(Btw: This approach also got me rid of "StaleElementException" stuff lots of times)
see:
org.openqa.selenium.support.events.EventFiringWebDriver
org.openqa.selenium.support.events.WebDriverEventListener
driveme = new ChromeDriver();
driver = new EventFiringWebDriver(driveme);
ActivityCapture handle=new ActivityCapture();
driver.register(handle);
=> ActivityCapture implements WebDriverEventListener
e.g. javascriptExecutor to deal with Ajax calls in a wicket/dojo techstack
#Override
public void beforeClickOn(WebElement arg0, WebDriver event1) {
try {
System.out.println("After click "+arg0.toString());
//System.out.println("Start afterClickOn - timestamp: System.currentTimeMillis(): " + System.currentTimeMillis());
JavascriptExecutor executor = (JavascriptExecutor) event1;
StringBuffer javaScript = new StringBuffer();
javaScript.append("for (var c in Wicket.channelManager.channels) {");
javaScript.append(" if (Wicket.channelManager.channels[c].busy) {");
javaScript.append(" return true;");
javaScript.append(" }");
;
;
;
javaScript.append("}");
javaScript.append("return false;");
//Boolean result = (Boolean) executor.executeScript(javaScript.toString());
WebDriverWait wait = new WebDriverWait(event1, 20);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return !(Boolean) executor.executeScript(javaScript.toString());
}
});
//System.out.println("End afterClickOn - timestamp: System.currentTimeMillis(): " + System.currentTimeMillis());
} catch (Exception ex) {
//ex.printStackTrace();
}
}
As #DebanjanB said, your button (or another element) could be temporarily covered by another element, but you can wait and click it even if you don't know which element is covering the button.
To do this, you can define your own ExpectedCondition with the click action:
public class SuccessfulClick implements ExpectedCondition<Boolean> {
private WebElement element;
public SuccessfulClick(WebElement element) { //WebElement element
this.element = element;
}
#Override
public Boolean apply(WebDriver driver) {
try {
element.click();
return true;
} catch (ElementClickInterceptedException | StaleElementReferenceException | NoSuchElementException e) {
return false;
}
}
}
and then use this:
WebDriverWait wait10 = new WebDriverWait(driver, 10);
wait10.until(elementToBeClickable(btn));
wait10.until(new SuccessfulClick(btn));
Try Thread.Sleep()
Implicit - Thread.Sleep()
So this isn’t actually a feature of Selenium WebDriver, it’s a common feature in most programming languages though.
But none of that matter.
Thread.Sleep() does exactly what you think it does, it’s sleeps the thread. So when your program runs, in the majority of your cases that program will be some automated checks, they are running on a thread.
So when we call Thread.Sleep we are instructing our program to do absolutely nothing for a period of time, just sleep.
It doesn’t matter what our application under test is up to, we don’t care, our checks are having a nap time!
Depressingly though, it’s fairly common to see a few instances of Thread.Sleep() in Selenium WebDriver GUI check frameworks.
What tends to happen is a script will be failing or failing sporadically, and someone runs it locally and realises there is a race, that sometimes WedDriver is losing. It could be that an application sometimes takes longer to load, perhaps when it has more data, so to fix it they tell WebDriver to take a nap, to ensure that the application is loaded before the check continues.
Thread.sleep(5000);
The value provided is in milliseconds, so this code would sleep the check for 5 seconds.
I was having this problem, because I had clicked into a menu option that expanded, changing the size of the scrollable area, and the position of the other items. So I just had my program click back on the next level up of the menu, then forward again, to the level of the menu I was trying to access. It put the menu back to the original positioning so this "click intercepted" error would no longer happen.
The error didn't happen every time I clicked an expandable menu, only when the expandable menu option was already all the way at the bottom of its scrollable area.

How to make selenium 3.4.0 wait for page load?

I am using selenium web driver 3.4.0 to find the response time of a website..In earlier version , I have used
WebDriver wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("myId"))); to find the page loaded.
But these two lines of code not working for version 3.4.0. is there any other way to calculate the load time of a page? Or wait until the page gets loaded? Also I need to detect the modal dialog which will be loaded on button click.
I am implementing using dynamic web project in eclipse IDE.
I also need to wait for some moment until some click event finished loading Dom element. Wait.until() is not working for selenium 3.4.0. how to make selenium wait until some element is visible ?
You can use JavascriptExecutor to get the ready state of the page, and pass it as an expected condition to your wait.until()
Here is the reference code for this,
ExpectedCondition<Boolean> expectation = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
}
};
try {
Thread.sleep(1000);
WebDriverWait wait = new WebDriverWait(LocalDriverManager.getDriver(), 30);
wait.until(expectation);
} catch (Throwable error) {
Assert.fail("Timeout waiting for Page Load Request to complete.");
}

Selenium, sendKeys to an element that´s not visible but selected [duplicate]

Here I have the image of my code and the image of my error. Can anyone help me to resolve this issue?
ElementNotInteractableException
ElementNotInteractableException is the W3C exception which is thrown to indicate that although an element is present on the HTML DOM, it is not in a state that can be interacted with.
Reasons & Solutions :
The reason for ElementNotInteractableException to occur can be numerous.
Temporary Overlay of other WebElement over the WebElement of our interest :
In this case, the direct solution would have been to induce ExplicitWait i.e. WebDriverWait in combination with ExpectedCondition as invisibilityOfElementLocated as folllows:
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("xpath_of_element_to_be_invisible")));
driver.findElement(By.xpath("xpath_element_to_be_clicked")).click();
A better solution will be to get a bit more granular and instead of using ExpectedCondition as invisibilityOfElementLocated we can use ExpectedCondition as elementToBeClickable as follows:
WebDriverWait wait1 = new WebDriverWait(driver, 10);
WebElement element1 = wait1.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath_of_element_to_be_clicked")));
element1.click();
Permanent Overlay of other WebElement over the WebElement of our interest :
If the overlay is a permanent one in this case we have to cast the WebDriver instance as JavascriptExecutor and perform the click operation as follows:
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
I got this because the element I wanted to interact with was covered by another element. In my case it was an opaque overlay to make everything r/o.
When trying to click an element UNDER another element we usualy get "... other Element would receive the click " but not always :.(
This Exception we get when the element is not in an interactable state. So we can use wait till the element is Located or become clickable.
Try using the Implicit wait:
driver.manage().timeouts().implicitlyWait(Time, TimeUnit.SECONDS);
If this is not working use Explicit wait:
WebDriverWait wait=new WebDriverWait(driver, 20);
WebElement input_userName;
input_userName = wait.until(ExpectedConditions.elementToBeClickable(By.tagName("input")));
input_userName.sendkeys("suryap");
You can use ExpectedCondition.visibilityOfElementLocated() as well.
You can increase the time, for example,
WebDriverWait wait=new WebDriverWait(driver, 90);
A solution to this for Javascript looks like this. You will have to modify the time to suit your need.
driver.manage().setTimeouts({ implicit: 30000 });
Hope this is helpful to someone.
see the docs for reference
Actually the Exception is Element Not Visible
The best practice is to use Implicit wait below driver Instantiation so it get sufficient time to find element throughout the exception
driver.get("http://www.testsite.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Still facing issue as some element require more time. Use ExplicitWait for individual element to satisfy certain condition
In your case you are facing element not visible exception then use wait condition in following way-
WebDriverWait wait = new WebDriverWait(driver, 120);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.your_Elemetnt));
In my case issue was because there is some animation, and that element is not visible for some duration. And hence exception was occurring.
For some reason I couldn't make ExpectedConditions.visibilityOfElementLocated work, so I created a code to wait for some hardcoded seconds before proceeding.
from selenium.webdriver.support.ui import WebDriverWait
def explicit_wait_predicate(abc):
return False
def explicit_wait(browser, timeout):
try:
Error = WebDriverWait(browser, timeout).until(explicit_wait_predicate)
except Exception as e:
None
And now I am calling this explicit_wait function wherever I want to wait for sometime e.g.
from selenium import webdriver
from selenium.webdriver.common.by import By
browser = webdriver.Safari()
browser.get('http://localhost')
explicit_wait(browser,5) # This will wait for 5 secs
elem_un = browser.find_element(By.ID, 'userName')

Explicit wait is not working for Firefox (52.4.0 (64-bit))

Explicit wait is not working for Firefox (52.4.0 (64-bit))below is my code:
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://XXXX/XXXXX/XX/login");
driver.findElement(By.id("userId")).sendKeys("XXXXX");
driver.findElement(By.id("password")).sendKeys("XXXXX");
driver.findElement(By.id("submit")).click();
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[text()='Viewer']")));
driver.findElement(By.xpath("//span[text()='Viewer']")).click();
}
I have to use Explicit wait here in any case as elements doesn't get loaded in fixed time. I have searched lot in google but didn't find any code working for me.
As per your code attempt it seems you are waiting for the WebElement through WebDriverWait and then trying to invoke click() method. In your code you have used the clause presenceOfElementLocated with ExpectedConditions, which as per the documentation doesn't confirms if the WebElement is Displayed and Enabled as well.
A better solution will be to modify the clause for ExpectedConditions where instead of presenceOfElementLocated we have to use elementToBeClickable as follows:
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Viewer']")));
You are using presenceOfElementLocated. As per documentation:
An expectation for checking that an element is present on the DOM of a
page. This does not necessarily mean that the element is visible.
You have to be sure that you are waiting on the element the correct expected condition.
as per #DebanjanB , i just it is not an good idea to use presenceOfElementLocated instead it is always better to use elementToBeClickable so correct code should be:
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://XXXX/XXXXX/XX/login");
driver.findElement(By.id("userId")).sendKeys("XXXXX");
driver.findElement(By.id("password")).sendKeys("XXXXX");
driver.findElement(By.id("submit")).click();
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Viewer']")));
driver.findElement(By.xpath("//span[text()='Viewer']")).click();
}

IEDriver implementation fails the test

I am using Webdriver(without IEDriver implementation) 2.23 API on windows7 machine with JDK7 and JRE7. The test scripts are working fine as expected but when i introduced IEDriver the script fails in a page with cannot click on element error message as that corresponding element is not visible. i have double checked with my application for the locator. The same can be clicked with out IEDriver implementation. I have tried by simulating all the click types including context click by Action class. No use. All click types returns the same result. Any help ?
Finally, i was manage to click the above said Element with the help of following code.
WebElement we = driver.findElement(By.name("Complete"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", we); // common for all we
The real source is here. This may helpful for someone.
As you say that the element is actually visible and the error's log says it is not, I think that the problem might be due to Internet Explorer's slowness. You could use this method for a quick test:
boolean isElementDisplayed(final WebDriver driver, final WebElement element, final int timeoutInSeconds) {
try {
ExpectedCondition condition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(final WebDriver webDriver) {
return element.isDisplayed();
}
};
Wait w = new WebDriverWait(driver, timeoutInSeconds);
w.until(condition);
} catch (Exception ex) {
//if you get here, it's because the element is not displayed after timeoutInSeconds
return false;
}
return true;
}
Use it like this:
WebElement we = driver.findElement(By.name("Complete"));
if (isElementDisplayed(driver, we, 30)) {
we.click();
}
This will make the driver wait (30 sec max.) till the element we becomes visible and then the driver clicks on it.
If it works, then my supposition is right and you could change the method for:
void clickOn(final WebDriver driver, final WebElement element, final int timeoutInSeconds) {
try {
ExpectedCondition condition = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(final WebDriver webDriver) {
element.click();
return true;
}
};
Wait w = new WebDriverWait(driver, timeoutInSeconds);
w.until(condition);
} catch (Exception ex) {
//probably some kind of exception thrown here
}
return;
}
and use it instead of we.click(), like:
WebElement we = driver.findElement(By.name("Complete"));
clickOn(driver, we, 30);
The code above is an approximation to let you check your issue in a quick and clear way and, if you end up using it, you should adapt it to your structure of code. This kind of utility code should never appear in your tests. Your test code should be clean and the same for all the environments (browsers, version, SOs, etc.). Keep the workarounds separately, e.g. some kind of util package.
Also, the method's signature is 'overweight'. Restructuring your util code, you should be able to write in your tests just this: clickOn(element).
Hope it helps ;)
UPDATE Actually, with these components I had never run into a similar problem:
selenium-server-standalone version 2.32.0
IEDriverServer_x64_2.30.1.exe

Resources