To Handle Popup message in selenium webdriver - selenium-webdriver

I am trying to click OK button on the popup window with the below selenium Webdriver code
driver.switchTo().alert().accept();
but i am geeting the Bellow error
org.openqa.selenium.NoAlertPresentException: No alert is present (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 2.22 seconds
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 20:21:45'
System info: os.name: 'Windows 2003', os.arch: 'x86', os.version: '5.2', java.version: '1.6.0_21'
Session ID: ddceb914-d74e-44c4-a159-9f1f591e7be1
Driver info: org.openqa.selenium.firefox.FirefoxDriver
here is the screenshot of the window

It may be a window and not an alert. Try following code:
String winHandle = driver.getWindowHandle(); //Get current window handle.
for(String windowsHandle : driver.getWindowHandles()) {
driver.switchTo().window(windowsHandle); //Iterate to the new window handle.
}
/*
Do any action on window or just close it.
*/
driver.close();
driver.switchTo().window(winHandle); //Switch to original window.

Related

Why some of the elements cannot be selected by Selenium webdriver?

I've been using Selenium webdriver for quite a while. Recently I came across this page: https://www.myagedcare.gov.au/service-finder
It seem very simple and I try to use id locator: bylocation
However, no matter how long I wait for the element to be ready by adding wait for some time, or wait for element to be ready like:
WebDriver driver = getDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(
ExpectedConditions.elementToBeClickable(By.id("byname")))
.click();
the element is never ready, and I always get error like "no such element: Unable to locate element:"
What might be going on? I've used locator for quite a while and I do not know how this can happen.
I am using chromedriver 2.30 and Chrome browser v.60.
A simple id locator like this in www.google.com does not give me any trouble. I tested it so that I do not think it's driver or browser issue.
Logs
net.serenitybdd.core.exceptions.SerenityWebDriverException: Timed out after 10 seconds waiting for visibility of element located by By.xpath: //input[#id='bylocation']
Build info: version: '2.46.0', revision: '61506a4624b13675f24581e453592342b7485d71', time: '2015-06-04 10:22:50'
System info: host: 'yun-PC', ip: '192.168.1.14', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_71'
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#id='bylocation']"}
(Session info: chrome=60.0.3112.50)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 20.04 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Try this xpath and let me know if it works,
//div[#id='edit-search-by--2']//label[normalize-space(text())='Location']/preceding-sibling::input[#type='radio']
Also try waiting for visibility of element and not for element to be clickable.
Edit:
The above Xpath is perfect. Problem was that the element was located in a frame.
Below code will get you going with the click part:
driver.get("https://www.myagedcare.gov.au/service-finder?tab=help-at-home");
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[#id='content']")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[#id='content']")));
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[normalize-space(text())='Location']/preceding-sibling::input[#type='radio']")));
WebElement location = driver.findElement(By.xpath("//label[normalize-space(text())='Location']/preceding-sibling::input[#type='radio']"));
WebElement name = driver.findElement(By.xpath("//label[normalize-space(text())='Name']/preceding-sibling::input[#type='radio']"));
location.click();
Thread.sleep(3000);
name.click();
driver.switchTo().parentFrame();
Click working video - https://www.screencast.com/t/0Fsw7gGZ
As the Radio Buttons are inside input tags, instead of id use xpath locator as follows:
WebDriverWait wait6 = new WebDriverWait(driver, 10);
WebElement radio_name = wait6.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='byname']/input[#id='byname']")));
radio_name.click();
Let me know if this Answers your Question.

Context menu isn't opened using Safari WebDriver

Unable to open context menu in Safari browser using SafariDriver Selenium. Getting following exceptions:
org.openqa.selenium.WebDriverException: Unknown command:
{"id":"az1mvyq9x4ly","name":"mouseMoveTo","parameters":
{"element":":wdc:1463726481487"}} (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 5 milliseconds
Build info: version: '2.52.0', revision: '4c2593c', time: '2016-02-11 19:06:42'
System info: host: 'RVSKCH19LT', ip: '192.168.10.30', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_11'
Driver info: org.openqa.selenium.safari.SafariDriver
Capabilities [{browserName=safari, takesScreenshot=true, javascriptEnabled=true, version=5.1.7, cssSelectorsEnabled=true, platform=WINDOWS, secureSsl=true}]
Session ID: null
try this code to resolve your issue.
WebElement obj = driver.findelement(by.xpath(""));
Action act = new Action(driver);
act.contextClick(obj).perform();
share your code review.
Actions/Interactions API is not implemented with SafariDriver yet.
Please try with the following JavaScript solution:
String script = "var element = document.querySelector('SOME_CSS_SELECTOR');var e = element.ownerDocument.createEvent(\"MouseEvents\"); e.initMouseEvent(\"contextmenu\", true, true, element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false,2, null); element.dispatchEvent(e);";
driver.executeScript(script);
Replace SOME_CSS_SELECTOR with the css selector of the element where you want the right click.

ElementNotVisibleError: Cannot click on element-error in Protractor IE browser

When I try to execute my protractor scripts in IE_11 browser I am getting following error.However same script working fine in chrome and Firefox browsers.Saying element is not visible.However when I execute the script manually by pausing the browser,respective element is visible.
ElementNotVisibleError: Cannot click on element (WARNING: The server did no
t provide any stacktrace information)
Command duration or timeout: 141 milliseconds
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 03:03:16'
System info: host: 'XXXXXX', ip: '10.XXX.CCC.33', os.name: 'Windows 7', os.arc
h: 'amd64', os.version: '6.1', java.version: '1.8.0_51'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreat
eProcessApi=false, pageLoadStrategy=normal, ie.usePerProcessProxy=false, ignoreZ
oomSetting=false, handlesAlerts=true, version=11, platform=WINDOWS, nativeEvents
=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLi
neSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBro
wserUrl=http://localhost:3653/, takesScreenshot=true, javascriptEnabled=true, ig
noreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEna
bled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 91db8197-e87b-4564-b1b4-9dd7389e19c6
It sounds like you are having timing issues. You might try using Expected Conditions functionality (http://www.protractortest.org/#/api?view=ExpectedConditions). It even looks like their example fits what you need:
var EC = protractor.ExpectedConditions;
var button = $('#xyz');
var isClickable = EC.elementToBeClickable(button);
browser.get(URL);
browser.wait(isClickable, 5000); //wait for an element to become clickable
button.click();

" StaleElementReferenceException: Element is no longer attached to the DOM " issue while running script. (Firefox browser)

My requirement is
Get all data from grid
Search specific text, if found
Click check box
My code is,
List<WebElement> totalRows = driver.findElements(By.xpath("//*[#id='ContentPlaceHolder1_ContentPlaceHolderChild_grdGroupSelection']/tbody/tr"));
System.out.println("Total Size: "+totalRows.size());
for (int count=1;count<totalRows.size()-1;count++){
System.out.println("Loop count: "+count);
WebElement rowElement = totalRows.get(count);
System.out.println("WebElement Tag name: "+rowElement.getTagName());
}
Unable to get the value from rowElement.
Here posted Logs, HTML source & snapshot for reference. Please help me out. Thanks in advance.
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM
Command duration or timeout: 294 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.43.1', revision: '5163bce', time: '2014-09-10 16:27:33'
System info: host: 'Saravanan-PC', ip: '192.168.101.22', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Session ID: 6ea5596b-9f0f-477b-9a11-dc534a0197ee
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=WINDOWS, databaseEnabled=true, cssSelectorsEnabled=true, javascriptEnabled=true, acceptSslCerts=true, handlesAlerts=true, browserName=firefox, webStorageEnabled=true, nativeEvents=false, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=35.0.1}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:187)
at org.openqa.selenium.remote.RemoteWebElement.findElementsByTagName(RemoteWebElement.java:264)
at org.openqa.selenium.By$ByTagName.findElements(By.java:323)
at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:163)
at com.aetherpal.scripts.ClientPolicyProfiles.selectCreatedCSPGroupID(ClientPolicyProfiles.java:95)
at com.aetherpal.scripts.ClientPolicyProfiles.main(ClientPolicyProfiles.java:80)
Caused by: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.43.1', revision: '5163bce', time: '2014-09-10 16:27:33'
System info: host: 'Saravanan-PC', ip: '192.168.101.22', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Driver info: driver.version: unknown
at .fxdriver.cache.getElementAt(resource://fxdriver/modules/web-element-cache.js:8325:24)
at .Utils.getElementAt(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:7922:10)
at .FirefoxDriver.prototype.findElementsInternal_(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:9636:32)
at .FirefoxDriver.prototype.findChildElements(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:9657:3)
at .DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:11612:16)
at .DelayedCommand.prototype.executeInternal_(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:11617:7)
at .DelayedCommand.prototype.execute/<(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:11559:5)
Grid:
HTML Source:
The checkbox, ID and the GroupName will be inside the tr.
Checkbox is the only input element inside the tr. You can use the following code which will wait for the checkbox of particular GroupName(in your case ACL all) to appear and click on it as soon as it is visible.
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//table[#id='ContentPlaceHolder1_ContentPlaceHolderChild_grdGroupSelection']//td[text()='ACL all']/..//input")));
element.Click();
The webpage might keep changing due to various reasons ie Reloading/Etc which are not very visible ,
Approach 1 :
One approach to this stale element exception is Trying to reduce the time between 'Find element' and 'Do some action on element'
Approach 2 :
Have a Repeated while loop to check the availablity of element until some condition is true , Also make sure to use Implicit/Explicit/Fluent waits , it helps a lot but never do a thread.sleep .
Finally I tried with JavascriptExecutor.executeScript() method. Its working fine...I don't know whether this approach is correct way or not..
my sample code is,
JavascriptExecutor scriptExecute = (JavascriptExecutor)driver;
WebElement el = (WebElement) scriptExecute.executeScript("var noOfRows =document.querySelectorAll('table[id=ContentPlaceHolder1_ContentPlaceHolderChild_grdGroupSelection]>tbody>tr'); " +
"for(var i=1;i<noOfRows.length-1;i++){" +
"return noOfRows[i]; }");
el.click();

6 text boxes, used click to find them, but sendKeys() is sending all text to the last text box

Following is the code i wrote for the text fields.
driver.findElement(By.xpath("//android.widget.RelativeLayout[1]/android.widget.EditText[1]")).click();
driver.findElement(By.xpath("//android.widget.RelativeLayout[1]/android.widget.EditText[1]")).sendKeys("Sathiya");
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.RelativeLayout[1]/android.widget.EditText[2]")).click();
driver.findElement(By.xpath("//android.widget.RelativeLayout[1]/android.widget.EditText[2]")).sendKeys("Rengarajan");
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[1]")).click();
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[1]")).sendKeys("sathiyarengarjan#setmore.com");
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[3]")).click();
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[3]")).sendKeys("3295739258");
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[4]")).click();
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[4]")).sendKeys("Ascendas");
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[5]")).click();
driver.findElement(By.xpath("//android.widget.RelativeLayout[3]/android.widget.EditText[5]")).sendKeys("Taramani");
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
First 5 clicks finds the exact text box, but when sendkeys is executed for the first 5 text boxes- all the values are getting entered into the 6th text box. When click is executed for the 6 text box, i am getting error stating unable to locate element. Any suggestions?
Server Logs:
An unknown server-side error occurred while processing the command. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 60.46 seconds
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
System info: host: 'SR6-SM-MACAIR.local', ip: '10.5.3.239', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.9.4', java.version: '1.7.0_21'
Session ID: 4d7c958f-9d8f-4989-8960-e2999cf83f75
Driver info: io.appium.java_client.AppiumDriver
Capabilities [{platform=LINUX, app=/usr/local/android-sdk/adt-bundle-mac-x86_64-20140702/sdk/platform-tools/SETMORE-ANDROIDAPP/Setmore.apk, javascriptEnabled=true, appActivity=com.adaptavant.setmore.ui.StartActivity, browserName=, networkConnectionEnabled=true, desired={platformVersion=4.4, app=/usr/local/android-sdk/adt-bundle-mac-x86_64-20140702/sdk/platform-tools/SETMORE-ANDROIDAPP/Setmore.apk, deviceName=Google Nexus 4, platformName=Android, browserName=, appActivity=com.adaptavant.setmore.ui.StartActivity, appPackage=com.adaptavant.setmore}, locationContextEnabled=false, appPackage=com.adaptavant.setmore, platformVersion=4.4, databaseEnabled=false, platformName=Android, deviceName=Google Nexus 4, webStorageEnabled=false, warnings={}, takesScreenshot=true}]
Not sure why you need back after each sendkeys.
Some problems in your code --
Also your Xpath is prone to errors if minor layout changes take place on the page.
You dont send implicit waits continuously in code.
Assuming all the textboxes are on same page in the visible area... you can do following --
a. Search for all editText(textboxes) like this--
elements = driver.get_webelements("//android.widget.EditText")
b) Send text to each textbox
for element in elements:
element.sendKeys("Hello world!");
If there more textboxes in same view but need scrolling, you will have to add scrolling logic there.
Note: code above is in python but I guess it should not be difficult for you to convert it over to Java

Resources