How to ignore the hidden element in selenium - java

I have written an script using selenium for user addition to an application. In which inside 'for loop' there is a Add_Button which will be visible at the start(i.e first user addition). While addiding the second user script will search for the hidden element Add_Button, but its not available so I am getting error:
org.openqa.selenium.ElementNotVisibleException: Cannot click on element
I need to skip the click of the Add_Button while second user addition in the for loop. I had tried the following codes, but no luck yet. Please help me with this.
1st try: Not working
if(browser.findElements(By.id("ext-gen72")).size()!=0){
browser.findElement(By.id("ext-gen72")).click();
}
2nd Try: Not working
int k=0;
boolean doneOnce=false;
do{
if (!doneOnce) {
//execute this only one time
browser.findElement(By.id("ext-gen72")).click();
doneOnce=true;
}
//rest of the code....
}While(k>10);

WebElement visible status can be found using isDisplayed() method if the element is present on page. If the element is not present on the page it will throw NoSuchElement exception.
if(browser.findElement(By.id("ext-gen72")).isDisplayed())
browser.findElement(By.id("ext-gen72")).click();
If element is not present on the page once clicked, you can use below code:
int k=0;
boolean clickOnce=true;
do{
if (clickOnce) {
browser.findElement(By.id("ext-gen72")).click();
clickOnce=false;
}
// rest of the code
}While(k>10);

((JavascriptExecutor)browser).executeScript("arguments[0].click();", browser.findElement(By.id("ext-gen72"));
Sometimes, a hidden element is visible on the page, but the driver just can't seem to get ahold of it. You can use JavaScriptExecutor to work around this by calling the javascript click() method on the element, provided that the element exists on the page.

try the following code
List<WebElement> elements = browser.findElements(By.id("ext-gen72")); if(elements.size()!=0){
for(WebElement element:elements){
if(element.isEnabled()){
element.click();
} }

Related

I am getting this error "stale element reference: element is not attached to the page document",

I am trying to add multiple products in to the cart
WebElement ele = driver.findElement(By.xpath("//li[text()='Grocery ']"));
//Creating object of an Actions class
Actions action = new Actions(driver);
//Performing the mouse hover action on the target element.
action.moveToElement(ele).perform();
Thread.sleep(3000);
driver.findElement(By.xpath("//li[#title='staples']")).click();
Thread.sleep(5000);
List<WebElement> products = driver.findElements(By.xpath("//div[#class='product-grid-img']"));
for(int i=0;i<products.size();i++)
{
products.get(i).click();
Thread.sleep(3000);
driver.findElement(By.xpath("(//span[text()='ADD TO CART'])[1]")).click();
driver.navigate().back();
driver.navigate().refresh();
}
As we can see, by clicking on a product a new page is opened so to get back you are navigating to the previous page explicitly and refreshing the page.
When you leaving the original page or refreshing it the elements collected by Selenium on that page becoming no more relevant AKA Stale.
You can read here or at any other online resource about this issue.
To make your code work you will have to get the product again.
Something like this should work:
List<WebElement> products = driver.findElements(By.xpath("//div[#class='product-grid-img']"));
for(int i=0;i<products.size();i++)
{
List<WebElement> products = driver.findElements(By.xpath("//div[#class='product-grid-img']"));
products.get(i).click();
Thread.sleep(3000);
driver.findElement(By.xpath("(//span[text()='ADD TO CART'])[1]")).click();
driver.navigate().back();
driver.navigate().refresh();
Thread.sleep(3000);
}
Every time you navigate to anywhere, your browser constructs a map of a sorts of the page, in memory. This is called the DOM. When you navigate somewhere else, the DOM is replaced with a new DOM of the new page. The browser does not keep a history of the DOMs you visited, so when you navigate back to somewhere you have already been, the browser has to construct the DOM again.
Let's look at the relevant parts of your code:
List<WebElement> products = driver.findElements(By.xpath("//div[#class='product-grid-img']"));
Find a bunch of elements in the current DOM.
for(int i=0;i<products.size();i++)
{
products.get(i).click();
First time navigate to another page. So discard all the elements you just found above and rebuild the DOM.
Second time through the loop, you are trying to use an element that is no longer found in the current DOM. Which throws the StaleElementException.
Thread.sleep(3000);
driver.findElement(By.xpath("(//span[text()='ADD TO CART'])[1]")).click();
driver.navigate().back();
Navigate again somewhere. Another rebuild of the DOM.
driver.navigate().refresh();
Will not help.
}
You will need to restructure your loop to find the element each time. Perhaps something like:
for(int i=0;i<products.size();i++)
{
// You will have to find the correct XPath here!
WebElement product = driver.findElement(By.xpath("//div[#class='product-grid-img'][" + i + "]"));
product.click();
Thread.sleep(3000); // You might want to use a proper wait here.
driver.findElement(By.xpath("(//span[text()='ADD TO CART'])[1]")).click();
driver.navigate().back();
}
StaleElementExceptions are caused by going to a new page and accessing old elements that are no longer valid.
You could do what others did and regrab the values or if it's in an a tag you could just collect all the hrefs and then just driver.get() to them removing the need to driver.navigate().back();
.getAttribute("href")
I just searched for your query in Google to check , with the intention to learn more about what exactly is the question and topic ,
I got this :
"People also ask"
(Q)How do you fix stale element reference element is not attached to the page document in selenium?
Solution : The element in the DOM is not found because your page is not entirely loaded when Selenium is searching for the element. To solve that, you can put an explicit wait condition that tells Selenium to wait until the element is available to be clicked on.
https://www.google.com/search?q=his+error+%22stale+element+reference%3A+element+is+not+attached+to+the+page+document%22%2C&sourceid=chrome&ie=UTF-8

java selenium element found but one click does not work

I have a piece of selenium code to look for a certain element and afterwards to click on this same element. The element is found, but after that, the click does not seem to do the trick. Here is the code for finding the element (unfortunately using xpaths, because there are no id's and it uses a lot of selfmade methods):
String taakButton = "Start taak button";
String xpathButton = "//td[contains(text(),'" + datumhelper.formateerDatumVoorFlowAanmaakdatum(SoapHelper.datumVoorAanvraag5SpaarrekeningSns) + "')]/following-sibling::*[4]/button";
WebElement startButton = selenium.searchForElementByXpathWithoutSwitchToFrame(xpathButton, taakButton);
I use the above String xpathButton to store a WebElement in a variable, after that I pass the WebElement to a method in a different class:
The searchForElementByXpathWithoutSwitchToFrame looks for the element and verifies if it is found.
WebElement startTaakButton = selenium.searchForElementByXpathWithoutSwitchToFrame(xpathStartTaakButton, taakButton);
The element is found, now click on it :
selenium.klikStartOfInzienTaak(startTaakButton, xpathStartTaakButton);
The klikStartOfInzienTaak method, which performs the click looks like this:
public void klikStartOfInzienTaak(WebElement webElementToBeClicked, String xpathToBeClicked) throws InterruptedException {
Actions action = new Actions(driver);
//check to see if element is not null
Assert.assertNotNull("WebElement 'startOfInzienTaak' niet gevonden", webElementToBeClicked);
//Thread.sleep(2500);
//I use Action doubleClick in the hope that would work.
action.moveToElement(webElementToBeClicked).doubleClick().build().perform();
I also used regular driver.click(). It seems the element is found because it does not give a NoSuchElementException and I see the focus is on the element to be clicked, but nothing happens:
Button to be clicked
When I uncomment the Thread.sleep it works, but I don't want to be using Thread.sleep.
As you can see in the image below with the loading image, the page seems to be (re)loading again after the element was already found and clicked on. Thats why the Thread.sleep works:
Button found and clicked but page (re)loading
Does anybody know what to do in order for me to remove the thread.sleep? Selenium has to somehow wait again for the page to reload again although the element is already found?
Try JavascriptExecutor to click the element,
Refer code,
WebElement element = driver.findElement(By.xpath(xpathButton));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You can use WebDriverWait function to first find the element in the webpage and then can click on the element. By this i didn't had to use thread.sleep.
WebDriverWait for_element = new WebDriverWait(20, TimeUnit.SECONDS);
for_element.until(ExpectedConditions.elementToBeClickable(driver.findElement(by what means u have to find the path);
dr.findElement().click();
Hope that this works for you as it worked for me!

How can I click div button in Selenium Java

Does anyone know how I can click (in Java) the button with following HTML code?
<div role="button" id=":t5.ss" class="c-N-K a-b a-b-va KMD69e-bU2Jkc-b DF" tabindex="0" aria-label="Join as John" style="user-select: none;">Join</div>
My snippet code in Java:
driver.get("https://www.somepage.com");
... enter new tab ...
Thread.sleep(10000);
driver.findElement(By.xpath("//div[#role='button']")).click();
And I've got
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
no such element: Unable to locate element
{"method":"xpath","selector":"//div[#role='button']"}
I've tried also following without success:
driver.findElement(By.xpath("//div[#id=':t5.ss']")).click();
driver.findElement(By.xpath("//div[#aria-label='Join as John']")).click();
driver.findElement(By.cssSelector("div[id=':t5.ss']")).click();
Selenium has methods named By.id() and By.className() to find the button and use click() to click the selected button.
driver.findElement(By.id("element id")).click()
OR
driver.findElement(By.className("element class")).click()
To click an element, it has to be visible and displayed.
WebElement e = find(...); //POM search
if (e != null){
Thread.sleep(...);
while (!e.isDisplayed())
Thread.sleep(...);
e.click();
}
This has worked for me a lot.
Using Thread.sleep in your tests is bad practice because you will never know if the page and the elements you want to use actually are finished loading.
It's better to use explicit waits. Here's an example:
new WebDriverWait(driver, timeout).until(ExpectedConditions.visibilityOfElementLocated(by));
More information about that can be found here.
The NoSuchElementException points towards three possibilities:
a) there simply is no such element that you are trying to find in the HTML
b) the element isn't loaded yet, if so use WebDriverWait
c) the element is part of an iframe and cannot be found unless you switch to that iframe
If c) is correct you can switch to the iframe with:
driver.switchTo().frame(d().findElement(iframe));
Instead of click(), try sendKeys().
Example:
myDiv.sendKeys(Keys.Enter); // or Keys.Return
You should use id as it is unique to identify the element
driver.findElement(By.id(":t5.ss")).click();
Also check if the element is displayed and enabled by using isDisplayed() and isEnabled() to click.

Selenium getting text input of Twingly (Java Code)

Please check out the element of this website.
It has a form, and along with 2 text input and 1 submit button.
I dont know which one from those 2 inputs that is actually used when the user type-in some urls over there.
But when I tried this (using firefoxDriver) to get the element:
WebElement textfieldURL = driver.findElement(By.id("ping-url")); // even ping-box not working
The result's unable to locate the element.
Then I change my code to this :
driver.switchTo().frame(driver.findElement(By.className("ping-iframe")));
WebElement textfieldURL = driver.findElement(By.id("ping-url")); // even ping-box not working
The result's still unable to locate the element.
Any clues?
You haven't mentioned the exception which you are facing. As your input tag present under iframe so you need to first switch into frame and than have to perform actions -
driver.switchTo().frame(driver.findElement(By.className("ping-iframe")));
//or you can use frame index as well
driver.switchTo().frame(0);
your element is available with the id ping-box . Try the following complete code -
System.setProperty("webdriver.gecko.driver","D:/Application/geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.twingly.com/ping");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.className("ping-iframe")));
driver.findElement(By.id("ping-box")).sendKeys("http://www.google.com");
driver.findElement(By.id("ping-button")).click();
Same is working for me.

How to move to next button if first one is disabled in Selenium Java?

enter image description hereI have 5 buttons with text "x", My Selenium script below only attempts to access the first which is disabled and moves on to another line of script written to do something else. All the x's have the same ID's and elements so I cannot call them separately.
How do I get my Selenium Java to check all 5 buttons before moving on to other task?
Selenium code:
driver.findElement(By.cssSelector("a.aui-button.aui-button-link.aui-restfultable-delete.aui-restfultable-delete-small")).click();
HTML:
×
You can see an example in the attached screenshot. The first x is disabled and I want my Selenium code to move to the next one.
You can use :not([disabled]) property in your css selector to get all button that are not disabled.
for your problem use below css selector,
a.aui-button.aui-button-link.aui-restfultable-delete.aui-restfultable-delete-small:not([disabled])
You can try with the following code which will check for aria-disabled attribute and according to that it will click on element:
List<WebElement> ele = driver.findElements(By.id("your id"));
for (int i = 0; i < ele.size(); i++) {
if (ele.get(i).getAttribute("aria-disabled") != "true") {
ele.get(i).click();
break;
}
}
Try to use below code:
// Selecting all the elements
List<WebElement> allele = driver.findElements(By.xpath(".//*[text()='x']"));
// Looping through the elements using for-each loop
for(WebElement eachEle : allele) {
// Checking whether the element is enabled or not
if(eachEle.isEnabled()) {
eachEle.click();
}
}
Hope this helps.

Categories

Resources