java selenium element found but one click does not work - java

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!

Related

Selenium not able to input element in the form inside fieldset tag

I have tried a different method to input elements like
Here is xpath I used
By NameOfTheProperty=By.xpath("//fieldset/div/input[#name='name']");
By NameOfTheProperty=By.xpath("//div/input[#name='name']");
By NameOfTheProperty=By.xpath("//input[#name='name']");
Tried with Selenium Builder
WebElement element=driver.findElement(by);
Actions builder = new Actions(driver);
Action mouseOverHome = builder
.moveToElement(element)
.click().sendKeys(text).build();
mouseOverHome.perform();
Tried with
WebElement element=driver.findElement(by);
element.sendKeys(text);
None of the methods is working..I can not able to input text inside the field and It shows
Element not interactable
Here is the site
I hope someone help me to find out the solution..
Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.
xpath you should checks is :
//input[#name='name']
if it is unique, then you can use Javascript executor :
WebElement password_input = driver.findElemenet(By.xpath("//input[#name='name']"));
((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('value', 'password_should_be_written_here')", password_input)
personally I would use id's if the element has one.
"//*[#id='__BVID__104']"
Make sure you are waiting for the element to be ready.
WebDriverWait wait = new WebDriverWait();
wait.until(ExpectedConditions.elementToBeClickable(element));
If it then times out on wait.until(... then I've found that sometimes an element must first be clicked for it to be exposed.
If this is the case. You will have to inspect the element before it is clicked. Find it's xpath, and see if it changes when it is clicked. If so then create a webElement for that element and have Selenium first click it, before clicking the actual field/element.

Element is clickable when ran in debug mode, but ran normally throws ElementClickInterceptedException

I am trying to do web automation.
I am defining a pop-up menu containing a button defined with either xpath or css respectively as
XPath:-->: //button[contains(text(), 'Open Door')
CSS:-->: div.device-item.content.view-content > div.detail > div > button.btn.btn-primary.ng-star-inserted
While all is well, it throws
org.openqa.selenium.ElementClickInterceptedException: element click intercepted:
when I am debugging the test one step at a time, it
runs successfully by clicking the button, with out any
problem. But when I am running the test, it fails. I hope it is not a wait issue, as we apply check waiting for
the presence of the button and verify it exists and clickable.
I believe many would advice to use JavaScriptExecutor approach, but our framework has a problem of returning any web element as a custom object called "Element" which is neither Web Element nor sub class of it, but extends Object and implements an interface called IElement, so we can't use JavaScriptExecutor method since it needs Web Element form of the button which we want to click on.
If it works in debug it means the overlay disappear automatically. You can wait for it to vanish
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("[id^='device-card']")));
And in any case you can wait for the button to be clickable
button = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(), 'Open Door')")));
button.click();
It will look something like:
driver.executeScript("document.querySelector('button.btn').click()")
Just adjust the css
There are a couple of things you need to take care:
XPath //button[contains(text(), 'Open Door'): This xpath can be optimized further in either of the formats:
//button[text()='Open Door']
//button[contains(., 'Open Door')]
CSS: div.device-item.content.view-content > div.detail > div > button.btn.btn-primary.ng-star-inserted looks good however I strongly believe button.btn.btn-primary.ng-star-inserted would also work.
"...Executes successfully in debug mode...": As the browser client gets ample time to settle the webpage dynamics and the desired WebElement gets enough time to get interactive.
"...we amply check waiting for the presence of the button and verify it exists and clickable...": Is a myth as:
presenceOfElementLocated(): Is the expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.
where as:
elementToBeClickable(): Is the expectation for checking an element is visible and enabled such that you can click it.
As your usecase is to invoke click() on the element you need to use the ExpectedConditions as elementToBeClickable().
Example:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("css_element"))).click();
You can find a detailed discussion in What is the most efficient way to wait for a page element (xpath) to show up in Selenium Webdriver?
Finally, when using the Selenium java clients, of coarse there are methods from JavascriptExecutor but that should be the last resort.
Update
As you are still seeing the error ...ElementClickInterceptedException: element click intercepted..., you can add an additional step to induce WebDriverWait for the invisibility and you can use either of the following options:
invisibilityOf(WebElement element):
new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOf(overlapping_webelement));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("css_clickable_element"))).click();
invisibilityOfElementLocated(By locator):
new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("css_overlapping_element")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("css_clickable_element"))).click();
You can find a relevant detailed discussion in Selenium invisibilityOf(element) method throwing NoSuchElementException + WebDriverWait.ignoring(NoSuchElementException.class) is not working
you can move the mouse to that element and then click on it, even I was facing this issue and this solution solved it
Actions clickOnBtn = new Actions(driver);
clickOnBtn .moveToElement("//button[contains(text(), 'Open Door')").click().build().perform;
this happens even when the element is not visible completely onscreen, in this case you can scroll to that element and then use the above code as shown below
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", ele);
Actions clickOnBtn = new Actions(driver);
clickOnBtn .moveToElement("//button[contains(text(), 'Open Door')").click().build().perform;
click element using javascriptExecutor
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
This even happens sometimes with the way we selected the element, the xpath can be changed, we can try to use a parent tag rather than the button and try
you can define your own ExpectedCondition with 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 it:
wait10.until(elementToBeClickable(btn));
wait10.until(new SuccessfulClick(btn));

Why does selenium click only the first line of code and not the two others?

I tested first if the first line of code to click the XPath which works but then when I add a second line of code to click By.name() it doesn't work, so I tried to change in XPath and then in CSS selectors but it only clicks the first one the (XPath code of line). I have tried but it doesn't seem to click the two other elements.
What I found out was that it only clicking what was on the first page, didn't really matter what was on the new page and I told to click on an element that I wanted to do. I'm using the Selenium version 3.141.59.
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ae65255\\Desktop\\java_gui\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://shop.palaceskateboards.com/collections/new");
driver.findElement(By.xpath("//*[#id=\"product-loop\"]/div[#data-alpha='S-LINE JOGGER BLACK']")).click(); //only this one work
driver.findElement(By.name("button")).click(); //second click dosen't work?
driver.findElement(By.linkText("Cart")).click(); //this dosen't work too?
}
Add some wait to let the page load before locating the element
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.name("button")));
button.click();
The third locator By.linkText("Cart") didn't work because the button doesn't have Cart text, it's in the data-text and value attributes.
As a side note, you should use By.partialLinkText() when looking for partial text.

JAVA/Selenium - clicking the first button on the page works 50% of the time

I'm using Selenium to automate some UI clicking for a web app. One one of the pages I have several buttons leading to some details. They all have the same name, but I'm ok with clicking either one, so I'm just clicking the first one. But... sometimes it works and sometimes it doesn't.
WebElement DetailsButton = setPresentElementByXpath("//input[1][#type='button' and #value='Go to Details']");
DetailsButton.click();
I'm using setPresentElementByXpath to dynamically wait for the element.
private WebElement setPresentElementByXpath(String xpath) throws Exception {
WebElement myDynamicElement = (new WebDriverWait(driver, 15))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
return myDynamicElement;
}
What am I doing wrong?
EDIT: I forgot to mention where it fails. It goes through DetailsButton.click(); without issues, but then it fails on clicking the next thing, the screenshots and logs say that the page that was supposed to be displayed after clicking the button was not there, so I'm assuming the button is not clicked.
Page load speed variation and caching might be the issue. If the element not found exception is happening, use an Explicit Wait for it to be clickable via ExpectedConditions.ElementToBeClickable(By).
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(By.id("myDynamicElement")));
If the exception "another element would receive the click" is happening you can click the element directly with the JavaScriptExecutor. Note: The JS action has no return value (if it worked or not) and does not wait for a page load if one happens after the click, like the Selenium .click() does.
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click()", element);

How to ignore the hidden element in selenium

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();
} }

Categories

Resources