no such element: Unable to locate element: when I use elementToBeClickable method - java

I have to wait for an element to appear and then click on it. Here is the code I tried and getting the NoSuchElementException.
I have 300 seconds to wait for the element, but it is trying to find the element:
tpo.fwOptimizationTestResults() without waiting for 300 seconds
WebElement fwResults = (new WebDriverWait(driver, 300))
.until(ExpectedConditions.elementToBeClickable(tpo.fwOptimizationTestResults()));
public WebElement fwOptimizationTestResults() {
//return driver.findElement(By.xpath("//*[#class='table table-condensed table-bordered']"));
return driver.findElement(By.xpath("//table[contains(#class, 'table-condensed')]"));
}
Error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//table[contains(#class, 'table-condensed')]"}
(Session info: chrome=75.0.3770.80)

The exception is not from elementToBeClickable, it's from fwOptimizationTestResults. You are using driver.findElement() which throws the exception and evaluates before the expected condition.
There are two overloads, elementToBeClickable(WebElement) and elementToBeClickable(By), you should use the second one
WebElement fwResults = (new WebDriverWait(driver, 300)).until(ExpectedConditions.elementToBeClickable(By.xpath("//table[contains(#class, 'table-condensed')]")));

You might want to amend your code to add ignoring stanza to the WebDriverWait
so it won't fail on NPEs:
WebElement fwResults = (new WebDriverWait(driver, 5))
.ignoring(NullPointerException.class)
.until(ExpectedConditions.elementToBeClickable(tpo.fwOptimizationTestResults()));
and in its turn put your WebElement function inside the try block and instead of throwing an exception - return null in case if element is not found:
public WebElement fwOptimizationTestResults() {
try {
return driver.findElement(By.xpath("//table[contains(#class, 'table-condensed')]"));
} catch (NoSuchElementException ex) {
return null;
}
}
More information:
FluentWait
How to use Selenium to test web applications using AJAX technology

Related

selenium.JavascriptException: javascript error: Function is not a constructor using WebDriverWait upgrading to Selenium 4.0 Java

We are running selenium and java automation project in chrome . it was running we want migrated to Micro soft Edge in that process we upgrade to Selenium 4.0 and java 1.8 edge 99. When we run the our project we are facing below error edge-browser
org.openqa.selenium.JavascriptException: javascript error: Function is not a constructor
Same code is working in chrome.
public void waitForLoad(long seconds) {
ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wd) {
try {
// this will tell if page is loaded
JavascriptExecutor js = (JavascriptExecutor) getDriver();
String windowState = js.executeScript("return document.readyState").toString();
//String windowState = (String) ((JavascriptExecutor) wd).executeScript("return document.readyState;");
log.debug("wait for window[" + wd.getWindowHandle() + "] sate:" + windowState);
log.debug("WINDOW is generated >>>>>");
return "complete".equals(windowState);
} catch (Exception e) {
log.debug("WINDOW is not loading>>>>>"+e);
return false;
}
}
};
long waitSeconds = seconds;
if(seconds<=0){
waitSeconds = ENV.getPageloadTimeout();
}
WebDriverWait wait = new WebDriverWait(driver, waitSeconds);
// wait for page complete
log.debug("PageLoadState>>"+pageLoadCondition.toString());
wait.until(pageLoadCondition);
We are facing issue in wait.until(pageLoadCondition); line in edge browser . Do any other way uset ExpectedConditio method
As you migrated from lower versions of Selenium to Selenium v4.0, the new constructor for WebDriverWait is updated as:
public WebDriverWait​(WebDriver driver, java.time.Duration timeout)
Wait will ignore instances of NotFoundException that are encountered (thrown) by default in the 'until' condition, and immediately propagate all others. You can add more to the ignore list by calling ignoring(exceptions to add).
Parameters:
driver - The WebDriver instance to pass to the expected conditions
timeout - The timeout when an expectation is called
and the implementation is as follows:
WebDriverWait wait = new WebDriverWait(testDriver, Duration.ofSeconds(1));
You need to change the defination of pageLoadCondition accordingly.
tl; dr
Class WebDriverWait

Updated the issue -Getting stale ELement Exception inspite of putting in try catch, waited until the Excepected element was visible

*Iam getting a stale element Exception in this part:
I am getting the id from the table
this is the part where it leads to stale element:
latestId.click();
I have tried: using the below code:
WebDriverWait wait = new WebDriverWait(driver,10);```
wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf(latestId)));
Basically in the method since both the id.click() and createdvalue("id",latestid.gettexxt()) is there it is causing the problem.
Can i get a solution for this ..Can Add more information if required*
You haven't share the element's ID finding code.
Here is was I advise you to do:
Find the element again by its known ID.
Wait for the element to be clickable
click on it
Code:
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement myElement = wait.until(ExpectedConditions.elementToBeClickable(By.id("TheID")));
try {
Actions builder = new Actions(browser);
builder.moveToElement(myElement).click().build().perform();
} catch (Exception x1) {
myElement.click();
}

Selenium Fluent Wait Implementation in the code still gives "org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:"

The mentioned URL in the code takes 5 seconds to display the login screen and in order to enter the details on the login page, I have implemented fluent wait for 10 seconds in my code. Even though the wait is correctly mentioned, for some reason this wait is not obeyed and i am always displayed with org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:
CODE:
public class FluentWaitDemo {
public static void main(String[] args) throws InterruptedException
{
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://app.hubspot.com/login");
By email = By.xpath("//input[#type='email']");
WebElement userId = FluentWaitForElement(driver, email);
userId.sendKeys("*******#gmail.com");
driver.close();
}
public static WebElement FluentWaitForElement(WebDriver driver, By locator)
{
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
return wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}
}
Error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#type='email']"}
(Session info: chrome=83.0.4103.97)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
To send a character sequence within the Email address field you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
Using cssSelector:
driver.get("https://app.hubspot.com/login");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#username"))).sendKeys("Bimlesh#gmail.com");
Using xpath:
driver.get("https://app.hubspot.com/login");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='username']"))).sendKeys("Bimlesh#gmail.com");
Browser Snapshot:
Reference
You can find a couple of detailed discussions on NoSuchElementException in:
Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element

Selenium Webdriver: How to wait untill progressbar vanishes and click on the button [duplicate]

I used explicit waits and I have the warning:
org.openqa.selenium.WebDriverException:
Element is not clickable at point (36, 72). Other element would receive
the click: ...
Command duration or timeout: 393 milliseconds
If I use Thread.sleep(2000) I don't receive any warnings.
#Test(dataProvider = "menuData")
public void Main(String btnMenu, String TitleResultPage, String Text) throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.findElement(By.id("navigationPageButton")).click();
try {
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(btnMenu)));
} catch (Exception e) {
System.out.println("Oh");
}
driver.findElement(By.cssSelector(btnMenu)).click();
Assert.assertEquals(driver.findElement(By.cssSelector(TitleResultPage)).getText(), Text);
}
WebDriverException: Element is not clickable at point (x, y)
This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.
The fields of this exception are :
BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL
DRIVER_INFO : public static final java.lang.String DRIVER_INFO
SESSION_ID : public static final java.lang.String SESSION_ID
About your individual usecase, the error tells it all :
WebDriverException: Element is not clickable at point (x, y). Other element would receive the click
It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).
Solution
The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:
1. Element not getting clicked due to JavaScript or AJAX calls present
Try to use Actions Class:
WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
2. Element not getting clicked as it is not within Viewport
Try to use JavascriptExecutor to bring the element within the Viewport:
WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
3. The page is getting refreshed before the element gets clickable.
In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.
4. Element is present in the DOM but not clickable.
In this case induce ExplicitWait with ExpectedConditions set to elementToBeClickable for the element to be clickable:
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));
5. 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")));
6. 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);
In case you need to use it with Javascript
We can use arguments[0].click() to simulate click operation.
var element = element(by.linkText('webdriverjs'));
browser.executeScript("arguments[0].click()",element);
I ran into this error while trying to click some element (or its overlay, I didn't care), and the other answers didn't work for me. I fixed it by using the elementFromPoint DOM API to find the element that Selenium wanted me to click on instead:
element_i_care_about = something()
loc = element_i_care_about.location
element_to_click = driver.execute_script(
"return document.elementFromPoint(arguments[0], arguments[1]);",
loc['x'],
loc['y'])
element_to_click.click()
I've also had situations where an element was moving, for example because an element above it on the page was doing an animated expand or collapse. In that case, this Expected Condition class helped. You give it the elements that are animated, not the ones you want to click. This version only works for jQuery animations.
class elements_not_to_be_animated(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
elements = EC._find_elements(driver, self.locator)
# :animated is an artificial jQuery selector for things that are
# currently animated by jQuery.
return driver.execute_script(
'return !jQuery(arguments[0]).filter(":animated").length;',
elements)
except StaleElementReferenceException:
return False
You can try
WebElement navigationPageButton = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();
Scrolling the page to the near by point mentioned in the exception did the trick for me. Below is code snippet:
$wd_host = 'http://localhost:4444/wd/hub';
$capabilities =
[
\WebDriverCapabilityType::BROWSER_NAME => 'chrome',
\WebDriverCapabilityType::PROXY => [
'proxyType' => 'manual',
'httpProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
'sslProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
'noProxy' => PROXY_EXCEPTION // to run locally
],
];
$webDriver = \RemoteWebDriver::create($wd_host, $capabilities, 250000, 250000);
...........
...........
// Wait for 3 seconds
$webDriver->wait(3);
// Scrolls the page vertically by 70 pixels
$webDriver->executeScript("window.scrollTo(0, 70);");
NOTE: I use Facebook php webdriver
If element is not clickable and overlay issue is ocuring we use arguments[0].click().
WebElement ele = driver.findElement(By.xpath("//div[#class='input-group-btn']/input"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
The best solution is to override the click functionality:
public void _click(WebElement element){
boolean flag = false;
while(true) {
try{
element.click();
flag=true;
}
catch (Exception e){
flag = false;
}
if(flag)
{
try{
element.click();
}
catch (Exception e){
System.out.printf("Element: " +element+ " has beed clicked, Selenium exception triggered: " + e.getMessage());
}
break;
}
}
}
In C#, I had problem with checking RadioButton,
and this worked for me:
driver.ExecuteJavaScript("arguments[0].checked=true", radio);
Can try with below code
WebDriverWait wait = new WebDriverWait(driver, 30);
Pass other element would receive the click:<a class="navbar-brand" href="#"></a>
boolean invisiable = wait.until(ExpectedConditions
.invisibilityOfElementLocated(By.xpath("//div[#class='navbar-brand']")));
Pass clickable button id as shown below
if (invisiable) {
WebElement ele = driver.findElement(By.xpath("//div[#id='button']");
ele.click();
}

Selenium Webdriver code works on debug but noy on a normal run

I'm trying to select an item on a listbox. The following code works when debugging the application but not on a normal run (as JUnit test)
wait.until(ExpectedConditions.elementToBeClickable(
By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")
));
driver.findElement(
By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")
).click();
wait.until(ExpectedConditions.elementToBeClickable(
By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")
));
driver.findElement(
By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")
).click();
Any ideas?
Try this code, it will wait for each second till 60 seeconds to find and click element:
int flag=0,wait=0;
while(flag==0 && wait<60){
try{
driver.findElement(By.xpath("//div[#id='ContentArea']/div/div/div[2]/div/table/tbody/tr[2]/td/div/span/span/span[2]/span")).click();
flag=1;
}
catch(Exception){
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
wait++;
}
}
flag=0,wait=0;
while(flag==0 && wait<60){
try{
driver.findElement(By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")).click();
flag=1;
}
catch(Exception){
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
wait++;
}
}
My theory would be that the state of the WebElement is changing between your wait.until call and the second time you resolve it to invoke click.
Rather than resolving the WebElement multiple times, call click() on the WebElement return value from your call to the WebDriverWait.
WebElement target1 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span")));
target1.click();
WebElement target2 =wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]")));
target2.click();
Or, if you don't want to store it as a temp var...
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='ContentArea']//tbody/tr[2]/td/div/span/span/span[2]/span"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[#id='symptomHeadGroupDropDown_listbox']/li[5]"))).click();

Categories

Resources