Driver is unable to find element on the page even when its present
. Basically Im just trying that when a popup (ad popup which we see in many website) is present it should get clicked. Below is the code :
System.setProperty("webdriver.gecko.driver","C:\\SeleniumDriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("https://www.sportskeeda.com/wwe");
//WebElement popup=driver.findElement(By.className("bullbg"));
WebElement popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]"));
if (popup.isDisplayed())
{
System.out.println("True");
}
else
{
System.out.println("False");
}
ERROR
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Unable to locate element: //div[contains(text(),'Close')]
Please click here to check there is a popup which gets display
Try scrolling to the element first, something might be in the way
WebElement element = driver.findElement(By.id("id"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Use Instead:
Boolean popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]")).isDisplayed();
if (popup == true)
{
System.out.println("True");
}
else
{
System.out.println("False");
}
Related
I use this code to click on
List<WebElement> list = driver.findElements(By.xpath("//div[#class='ag-center-cols-container']//div"));
// check for list elements and print all found elements
if(!list.isEmpty())
{
for (WebElement element : list)
{
// System.out.println("Found inner WebElement " + element.getText());
}
}
// iterate sub-elements
for ( WebElement element : list )
{
System.out.println("Searching for " + element.getText());
if(element.getText().equals(valueToSelect))
{
new WebDriverWait(driver, 30).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[#class='overlay ng-star-inserted']")));
element.click();
break; // We need to put break because the loop will continue and we will get exception
}
}
But from time to time I get this error at this line element.getText():
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
Do you know how I can implement a lister in order to fix this issue>
org.openqa.selenium.StaleElementReferenceException:
Indicates that a reference to an element is now "stale" --- the element no longer appears on the DOM of the page. The reason for this expectation is may be your DOM got updated or refreshed. For an example, after performing an action like click() your DOM may get updated or refreshed. In this time when you are trying to find an element on DOM you will experience this error.
You have to re-find that element in updated or refreshed DOM
But from time to time I get this error at this line element.getText():
Create a reusable method to handle this exception.
Code:
public static String getTextFromElement(WebElement element, WebDriver driver) {
try {
return element.getText();
} catch (org.openqa.selenium.StaleElementReferenceException e) {
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOf(element));
return element.getText();
}
}
For example, you can call in this way.
System.out.println("Found inner WebElement " + getTextFromElement(element, driver));
Below Is the site page
I'm trying to click on Continue to Netbanking button. But I am unable to do that. I have used xpath but its not working. Here is xpath which I've tried :
driver.findElement(By.xpath(".//*[#id='wrapper']/div[6]/a/img")).click();
Steps:
Open URl http://www.hdfcbank.com
Click on Login button on website. New popup will get open.
Click on "Continue on Netbanking". THIS IS NOT WORKING
Here is code:
driver.findElement(By.id("loginsubmit")).click();
Thread.sleep(3000);
Set<String> set = driver.getWindowHandles();
Iterator<String> it = set.iterator();
System.out.println(set.size());
for( String windowTab : set){
if(!windowTab.equalsIgnoreCase(MainWindow)){
driver.switchTo().window(it.next());
driver.manage().window().maximize();
String Wdinw2 = driver.getWindowHandle();
Thread.sleep(10000);
System.out.println(driver.getTitle());
driver.findElement(By.xpath(".//*[#id='wrapper']/div[6]/a/img")).click();
break;
}
}
Console :
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
no such element: Unable to locate element:
{"method":"xpath","selector":".//*[#id='wrapper']/div[6]/a/img"}
Try to use below code and let me know the result:
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);}
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("img[alt='continue']"))).click();
To switch back to main window (if you need):
driver.switchTo().window(winHandleBefore);
The Code is:
public void setRing(int index, String ringPattern) throws InterruptedException {
List<WebElement> webElementList = driver.findElements(By.xpath(an.getProperty("an_ringPattern")));
webElementList.get(index).click();
List<WebElement> options = webElementList.get(index).findElements(By.tagName("option"));
for (WebElement element : options) {
if (element.getText().equals(ringPattern)) {
element.click();
Thread.sleep(2000);
}
}
}
When I execute this code in debug mode, it is working fine. It selects whatever value I pass to the method.
But when I run this code it is not able to change the value in the drop down. It selects the value in the drop down, but it's not able to set the value.
Please let me know if I am missing something.
If the Exception .Error message display below at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80) is being thrown, means that somehow that element is not ready on the frame, the driver is not on that frame or the xpath is wrong.
You can try to switch to the frame where the element is located, like this: driver.switchToFrame("here goes the id of the frame"); You can inspect the ID of the frame or sometimes just passing the integer 0 works. Also, I would rather use wait1.until(ExpectedConditions.visibilityOfElementLocated(element)); instead of wait1.until(ExpectedConditions.presenceOfElementLocated(element));.
When you use presenceOfElementLocated, you cant assure that the element is visible for the driver.
You can use explicit wait in selenium - WebDriverWait
Use below modified code
public void setRing(int index, String ringPattern) throws InterruptedException {
List<WebElement> webElementList = driver.findElements(By.xpath(an.getProperty("an_ringPattern")));
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.presenceOfElementLocated(webElementList.get(index)));
webElementList.get(index).click();
List<WebElement> options = webElementList.get(index).findElements(By.tagName("option"));
for (WebElement element : options) {
WebDriverWait wait1 = new WebDriverWait(driver, 60);
wait1.until(ExpectedConditions.presenceOfElementLocated(element));
if (element.getText().equals(ringPattern)) {
element.click();
Thread.sleep(2000);
}
}
}
I am reaching to a page after clicking on a link.I have not clicking anything on that page yet. Still, As soon as the page loaded it throws an error:
Element not found in the cache - perhaps the page has changed since it was looked up
List<WebElement> securityGroup = driver.findElements(By.cssSelector("td[class='button-col']>a:nth-of-type(2)"));
System.out.println(securityGroup.size());
Thread.sleep(5000);
for(WebElement link:securityGroup) {
String b= link.getAttribute("href");
boolean a= b.contains(data0);
if(a){
System.out.println(b);
Thread.sleep(5000);
System.out.println("before clicking link");
link.click();
//After this new page opens and above error comes.**
}else {
System.out.println("No match found");
}
}
Thread.sleep(5000);
Select sel = new Select(driver.findElement(By.xpath("//select[#name='groupId']")));
System.out.println(sel.getOptions().toString());
sel.selectByValue("TEST");
This is because of the for loop.
You are finding the securityGroup which is a list and you are iterating through the list. In this for loop, you look for a condition and if yes you proceed to click on the link. But the issue here is that the list iteration is not complete and the for loop continues. But it wont find the String b= link.getAttribute("href"); of the next iteration because you are on a new page.
Use a break to break the loop once the condition is satisfied.
if(a){
System.out.println(b);
Thread.sleep(5000);
System.out.println("before clicking link");
link.click();
break;
}else {
System.out.println("No match found");
}
there is not enough time to load the page and take the element:
driver.findElement(By.xpath("//select[#name='groupId']"))
try to do ImplicitlyWait after you init the driver
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
and Thread.sleep(5000); is bad idea using with selenium, for waiting you have selenium methods
When you click on link and redirected to another page the driver looses securityGroup. That's what causing the exception.
You need to relocate securityGroup each itreation
List<WebElement> securityGroup = driver.findElements(By.cssSelector("td[class='button-col']>a:nth-of-type(2)"));
int size = securityGroup.size();
for (int i = 0 ; i < size ; ++i) {
securityGroup = driver.findElements(By.cssSelector("td[class='button-col']>a:nth-of-type(2)"));
WebElement link = securityGroup.get(i);
String b = link.getAttribute("href");
boolean a = b.contains(data0);
if(a) {
System.out.println(b);
Thread.sleep(5000);
System.out.println("before clicking link");
link.click();
}
else {
System.out.println("No match found");
}
}
I have written a piece of code to login into an application which is working fine. Now I have to click an add button, and I have tried it by Id, XPath, ClassName but it just gives me the exception of element not found. I thought I should apply an explicit wait, but it also did not work. Please check my code below:
public static void Login()
{
Browser.Url = "http://example.com";
_username = Browser.FindElement(By.Id("UserName"));
var password = Browser.FindElement(By.Id("Password"));
var loginbtn = Browser.FindElement(By.ClassName("btn-primary"));
_username.SendKeys("admin");
password.SendKeys("123");
loginbtn.Click();
var supplierTab = Browser.FindElement(By.Id("mainSupplier"));
supplierTab.Click();
WebDriverWait wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(20));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
try
{
return d.FindElement(By.Id("btnAddSupplier_SupplierForm"));
}
catch
{
return null;
}
});
var addbtn = Browser.FindElement(By.Id("btnAddSupplier_SupplierForm"));
addbtn.Click();
}
This always gives an exception on the second last line of code that element not found.
Here is the HTML:
Try the following
public static void Login()
{
Browser.Url = "http://example.com";
_username = Browser.FindElement(By.Id("UserName"));
var password = Browser.FindElement(By.Id("Password"));
var loginbtn = Browser.FindElement(By.ClassName("btn-primary"));
_username.SendKeys("admin");
password.SendKeys("123");
loginbtn.Click();
//I think you have mentioned the iframe exist and assuming the element is inside the iframe do the following. If not skip the SwitchTo() part
//you can use name, css to identify the iframe
Browser.SwitchTo().Frame(Browser.FindElement(By.XPath("xpath for the iframe")));
var supplierTab = Browser.FindElement(By.Id("mainSupplier"));
supplierTab.Click();
WebDriverWait wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(20));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id("btnAddSupplier_SupplierForm"));
});
//if you think the id is not unique try using xpath or css
//even though you added an explicit wait you never used it
myDynamicElement.Click();
}
Sometimes the element will be existing in the source code but will not be visible for selenium to perform a click operation. Try the below code which will wait until the element is visible:
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
IWebElement element = wait.Until(
ExpectedConditions.ElementIsVisible(By.Id("btnAddSupplier_SupplierForm")));
element.Click();
Not sure if this would help, but try calling this function before you click on Add button:
void waitForPageLoad(WebDriver driver)
{
ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
wait.until(pageLoadCondition);
}
A NoSuchElementException is thrown when the locating mechanism used is not available in the dom.
A TimeoutException is thrown when your expected condition fails to be true within the time limit. An expected condition can be anything, (exists,visibility,attribute value etc...).
First you want to figure out if the element's locating mechanism you are using is indeed not found in the dom. Here is a good way to manually find out.
Open chrome and navigate to the page.
Open chrome dev tools and click on the console tab.
In the text box type $x("//*[#id='btnAddSupplier_SupplierForm']") and hit enter. This will run an xpath query, basically you are looking for any element that has an id attribute with value "btnAddSupplier_SupplierForm".
If an element appears in the console and is the correct element then it's likely that you are trying to find an element in the dom before the dom is finished loading. If no element appears in the console then you have a bad locator.
Please report your findings.