Unable to click on pop up screen - java

After entering values to few fields i click on submit button which produces a pop up screen where i should click go button. I tried below code, it worked once but not working now. Please help
WebDriverWait wait = new WebDriverWait(driver, 6);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='lets_go']")));
driver.findElement(By.xpath(".//*[#id='lets_go']")).click();
How to fix ?

If it's an alert the use:
driver.switchto().alert().accept().
If pop up is a window, then first switch to that window using WindowHandler, then click on element

ExpectedConditions.visibilityOfElementLocated is used for checking that an element is present on the DOM of a page and visible, if this condition true within given time limit, it returns WebElement otherwise throws TimeOutException, So There is no need to find element again, omit last line and try as below :
WebDriverWait wait = new WebDriverWait(driver, 6);
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("lets_go")));
el.click();

I would suggest pasting the snippet of code for that "popup" to get your code working along with stack trace of error you are getting.
Also, you can go through http://www.softwaretestinghelp.com/handle-alerts-popups-selenium-webdriver-selenium-tutorial-16/. It gives you clear idea when it comes to handling popup.

Related

Selenium says element clicked 'successfully', but, it is not actually clicked

I have a scenario where I need to click Continue button.Even I gave print message after click function.The message is printing but the button is not clicking.I have tried java script executor,explicit wait(elementtobeclickable)But still its not clicking.What is the other solution.
This is what I have tried till now
By click_continue= By.xpath("//input[#id='btnWFContinue']");
if(driver.findElement(click_continue)!=null) {
waitVar.until(ExpectedConditions.elementToBeClickable(driver.findElement(click_continue)));
WebElement ele = driver.findElement(click_continue);
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
log.info("Clicked on Continue!!!");
/*
WebElement element = driver.findElement(click_continue);
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
driver.findElement(click_continue).click(); */
}else {
log.info("Continue button is not present moving to next step");
}
Open the desired page in your browser and open the browser console . Execute the below code in the same
$("input[id='btnWFContinue']").click() or document.getElementById("btnWFContinue").click()
If the element is clickable , then the above javascript command must change the webpage. Use the same in your script as well. Other there is no click event associated with your element.
try placing a wait statement before your if statement. Its possible that the code executes before the elemnt is loaded and the code jumps to the else part.

Unable to click on webelement button

Unable to click on webelement button
I tried to click on button by mouse movement but no success
my outer html is as below :
<button class="btn btn-alt btn-small" type="button" ng-click="ecdapp.uploadBlueprintModalPopup();">
Create
</button>
button xpath is:
//*[#id="page-content"]/div[3]/button
Not seeing the full page source it's hard to tell where your XPath expression is good or not, you can try locating the button using its text instead
//button[normalize-space(text())='Create']
the normalize-space() function is used to discard heading/trailing whitespaces
It might also be the case the button is not immediately available, I would recommend considering using Explicit Wait approach via WebDriverWait class
WebElement myButton = new WebDriverWait(driver, 10)
.until(ExpectedConditions
.elementToBeClickable(By.xpath("//button[normalize-space(text())='Create']")));
myButton.click();
the above code will try to locate the aforementioned button for 10 seconds and click it as soon as it will be present/visible/clickable. Otherwise it will fail with NoSuchElementException
May be the Xpath is wrong. Try the below xpath:
//button[contains(text(),'Create')]
As you can see on the screenshot this Xpath 100% works, if you still won't be able to click on that button, then problem is not with xpath. Let me know if its still fails.
By.xpath("//button[#class = 'btn btn-alt btn-small' and #type = 'button']")
Based on your comment:
I tried this code , but unable to click . element click intercepted: Element ... is not clickable at point (293, 97). Other element would receive the click: ... (Session info: chrome=74.0.3729.169)
I pretty sure I know whats your problem, before u click on this element, something going on the page:
It says - Other element would receive the click, means there is other element above(overlapping) your button(pop up window, page is greyed out(disabled while loading, Some JS running)), so when Selenium trying to click on your button its actually clicking on that blocking element.
Try to click after Thread.Sleep(); wait 5-10 sec.
If this is the case then u need to add condition before find your button to check that element that prevent from clicking on button is disappeared then u click on it.
Try JavaScript executors as below,
WebElement element = driver.findElement(By.xpath("<xpath of button>"));
JavascriptExecutor js= (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);

Xpath issue in element location

I am getting a very long xpath for an element that I selected. Is there anyway to shorten it? This is the xpath I am getting:
//li[#class='menu_men 1-level hasChild']//div[contains(#class,'level-2')]//div[#class='menu-wrapper']//ul[#class='level-2']//li[#class='1-level']//div[#class='level-3']//ul[#class='level-3']//li//a[#class='level-3'][contains(text(),'Socks')]
This is the URL: Calvin Klein Singapore I hovered over 'MEN', the accessories section will appear, than I hover the 'Socks' to get the xPath.
I am getting the following execption in my code and I am wondering if somehow the long xpath could be one of the reasons:
org.openqa.selenium.NoSuchElementException: no such element: Unable to
locate element: {"method":"xpath","selector":"//li[#class='first
menu_men 1-level
hasChild']//div[contains(#class,'level-2')]//div[#class='menu-wrapper']//ul[#class='level-2']//li[#class='1-level']//div[#class='level-3']//ul[#class='level-3']//li//a[#class='level-3'][contains(text(),'Socks')]"}
I am using cropath from within chrome developer tools to get the xPath.
I am new to automation, I really hope someone can advise. Thank you.
#SameerArora this is the code I have to clear the pop up window, as what I had mentioned in the comments below.
//for clearing the popup window
#FindBy(how=How.XPATH,using="//*[starts-with(#id,'popup-subcription-closes-link-')]")
public WebElement newsletterpopup;
public String clickCategory(){
//.....
resusableFunctions.buttonClick(driver, newsletterpopup, "popoup");
}
public void buttonClick(WebDriver driver, WebElement element, String elementName) throws InterruptedException
{
try
{
element.click();
System.out.println("Log: ResuableFunction.buttonClick");
}
catch (org.openqa.selenium.ElementNotInteractableException notInteract)
{}
The element you are looking for can be found using xpath:
WebElement element = driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]"));
However, as the element is not visible directly when you are opening the link, you would be getting NoSuchElementException, so to resolve it you can use javascript click method on the element which directly operates on the div of the page.
Addition to this, i can see that a subscription popup comes when i am opening the page for the first time, so you need to dismiss that popup first(if the popup is present) and then click on the "Socks" element using the JavaScript click method.
Your code should be like:
List<WebElement> closeSubscriptionPopUp = driver.findElements(By.xpath("//a[contains(#id,'popup-subcription-closes-link')]"));
if (closeSubscriptionPopUp.size() > 0) {
closeSubscriptionPopUp.get(0).click();
}
WebElement sockElement = driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", sockElement);
To hovered over 'MEN' >> accessories >> 'Socks' section, You need to use selenium Actions class.
As it is not really possible to first click on men(as it will open other section),
So to hover to sock, you need to chain all of the actions that you want to achieve in one go.
Process should be:
move to men element first
Move to accessories
then move to Socks and click on it.
Note: By using Action class, we can chain all the process in one single go.
As mentioned below
1) First way:
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'MEN')])[2]")))
.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]")))
.click().build().perform();
2) Second way with wait:
WebDriverWait wait= new WebDriverWait(driver, 10);
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'MEN')])[2]"))).build().perform();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//a[contains(text(),'Socks')])[1]")));
action.moveToElement(driver.findElement(By.xpath("(//a[contains(text(),'Socks')])[1]")));
action.click().build().perform();
Try this:
//a[normalize-space(text()) = 'Socks']
I would recommend you to not use such long xpath's and try to write xpath on your own.
Try :
//li[contains(#class,'menu_men')]//a[contains(text(),'Socks')]

Selenium: Clicked Element changes depending on number of instance launched

So I'm just trying to get the value of a input textbox after clicking a radiobutton related to it. I have 3 radiobuttons, let's call them "radio1" "radio2" and "radio3"
By default, "radio3" is checked, my goal is to click "radio1" and then get the value of the textbox. Here is the code I'm running:
WebElement radioMonthly = driver.findElement(By.xpath("//*
[#id=\"dateFromTo_date_format_2\"]"));
Actions actions = new Actions(driver);
actions.moveToElement(radioMonthly).click().perform();
At first attempt, "radio1" is clicked and the value stored properly, but if I launch the test again, it's "radio2" the clicked one. Note that they don't share id.
I already fixed the issue but I would like to know what's going on here
Thanks
Here is how I fixed it, following this thread on SO
Debugging "Element is not clickable at point" error
And the code:
WebElement radioMonthly =
driver.findElement(By.xpath("//[#id=\"dateFromTo_date_format_2\"]"));
JavascriptExecutor clickradioMonthly = (JavascriptExecutor)driver;
clickradioMonthly.executeScript("arguments[0].click()", radioMonthly);
But still will be great if someone is able to understand and explain whats going on the question
Thanks

Selenium -- How to wait until page is completely loaded [duplicate]

This question already has answers here:
Wait for page load in Selenium
(48 answers)
Closed 6 years ago.
I am trying to automate some test cases using Java and Selenium WebDriver. I have the following scenario:
There is a page named 'Products'. When I click on 'View Details' link
in the 'Product' page, a popup (modal-dialog) containing the details of the item appears.
When I click on the 'Close' button in the popup the popup closes and
the page automatically refreshes (the page is just reloading, the contents remain unchanged).
After closing the popup I need to click on 'Add Item' button in the
same page. But when WebDriver trying to find the 'Add Item' button,
if the internet speed is too fast, WebDriver can find and click the
element.
But if the internet is slow, WebDriver finds the button before the
page refresh, but as soon as the WebDriver click on the button, the page refreshes and StaleElementReferenceException occurs.
Even if different waits are used, all the wait conditions become true
(since the contents in the page are same before and after reload)
even before the page is reloaded and StaleElementReferenceException
occurs.
The test case works fine if Thread.sleep(3000); is used before clicking on the 'Add Item' button. Is there any other workaround for this problem?
3 answers, which you can combine:
Set implicit wait immediately after creating the web driver instance:
_ = driver.Manage().Timeouts().ImplicitWait;
This will try to wait until the page is fully loaded on every page navigation or page reload.
After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:
C#
new WebDriverWait(driver, MyDefaultTimeout).Until(
d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
Java
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Check if the URL matches the pattern you expect.
It seems that you need to wait for the page to be reloaded before clicking on the "Add" button.
In this case you could wait for the "Add Item" element to become stale before clicking on the reloaded element:
WebDriverWait wait = new WebDriverWait(driver, 20);
By addItem = By.xpath("//input[.='Add Item']");
// get the "Add Item" element
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(addItem));
//trigger the reaload of the page
driver.findElement(By.id("...")).click();
// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));
// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(addItem)).click();
You can do this in many ways before clicking on add items:
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid"))); // instead of id you can use cssSelector or xpath of your element.
or:
wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
You can also wait like this. If you want to wait until invisible of previous page element:
wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait and its documentation.
yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again
understand it with a dummy code
// clicking on view details
driver.findElement(By.id("")).click();
// closing the pop up
driver.findElement(By.id("")).click();
// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost
// so to overcome this you have to re identify the locator strategy for add item
// Please note : this is one of the way to overcome stale element exception
// Step 1 please add a universal wait in your script like below
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser
There are two different ways to use delay in selenium one which is most commonly in use. Please try this:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
second one which you can use that is simply try catch method by using that method
you can get your desire result.if you want example code feel free to contact me defiantly I will provide related code

Categories