Why some of the elements cannot be selected by Selenium webdriver? - 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.

Related

How to Automate cascading drop downs using selenium webDriver

I am facing issue while automating cascading drop down. Functionality is like this: On clicking drop down list and selecting one value, it will open another drop down according to the value selected in parent drop down.
Please find screenshots here: CLICK HERE
Here is my code:
Utility.SelectDropdown(driver, "//div[3]/div/div/select", "Test 1");
Utility.SelectDropdown(driver, "//div[2]/div/div/div[3]/div/div/select", "Test 2");
Utility.SelectDropdown(driver, "//div[3]/div/div/div[3]/div/div/select", "Test 3");
Utility class:
public static void SelectDropdown(WebDriver driver,String xpath,String value){
WebElement ele= driver.findElement(By.xpath(xpath));
Select dropdown=new Select(ele);
dropdown.selectByVisibleText(value);
I tried this using Wait and tab out, But it didn't work.
It is selecting value in first drop down but unable to load child drop down. Hence I am getting error message like this:
" Cannot locate element with text: Test 2."
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_111'
Here is HTML of drop down:Click Here
Suggestions for this query will be appreciated.
Thank you.
Above issue was resolved with the help of keys function.
WebElement element8 = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("manPosDropD1_xpath"))));
element8.click();
element8.sendKeys(Keys.ARROW_DOWN);
element8.sendKeys(Keys.ENTER);
Thank you.

" 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

Selenium Caching Issue w/ Nightwatch.js Integration Tests

I have a small, but growing (hopefully) suite of integration tests that I've built using Nightwatch.js (v0.5.6) on top of the Selenium webdriver (v2.41.0). I've always gotten the occasional Element not found in the cache error, but I'm working on a large validation test case - a file that contains over 2 dozen individual tests plus setUp(). I haven't been able to finish running this test yet and that's a problem.
There was an error while executing the Selenium command - enabling the --verbose option might offer more details.
Element not found in the cache - perhaps the page has changed since it was looked up
The error always seems to occur right at the end of my setUp() function, but I can't find the answer that will prevent this caching from happening. Here's my setUp() function:
setUp: function(browser) {
console.log('Logging in & navigating to Eligibility Groups...');
login(browser, app.masterAdminUsername, app.masterAdminPassword)
// Navigate to Eligibility Groups
.waitForElementVisible('button[data-action="EligibilityGroups"]', 1000, function() {
browser
.click('button[data-action="EligibilityGroups"]', function() {
console.log('Link clicked. Waiting for #btnCreate to be visible');
browser
.waitForElementVisible('#btnCreate', 1000, function() {
console.log('Exiting setUp()');
});
});
})
}
Eventually, I get this:
There was an error while executing the Selenium command - enabling the --verbose option might offer more details.
Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 3.72 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.41.0', revision: '3192d8a', time: '2014-03-27 17:17:32'
System info: host: 'robwilkerson.local', ip: '172.20.1.112', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.9.4', java.version: '1.6.0_65'
Session ID: 04f47f5c-fda0-f049-9ec1-1d3a40ac44fe
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=MAC, acceptSslCerts=true, javascriptEnabled=true, browserName=firefox, rotatable=false, locationContextEnabled=true, version=30.0, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=true, nativeEvents=false, webStorageEnabled=true, applicationCacheEnabled=true, takesScreenshot=true}]
✖ Timed out while waiting for element <#btnCreate> to be visible for 1000 milliseconds. - expected "visible" but got: not visible
The test case varies, but it always seems to fail "while waiting for element <#btnCreate> to be visible for 1000 milliseconds". Changing the number of ms I wait only changes the number of ms reported in the error.
What can I do here? Is there something wrong with my scripts? Everything I've read and everything I've tried has gotten me nowhere.
In case anyone drops by, what I've found through trial and error is:
Virtually any time a .click() loads or reloads content, I need to add a .pause(). Usually, .pause(1000) is sufficient, but longer is occasionally necessary. Using .waitForElementVisible() alone rarely works consistently.
Whenever I do use .waitForElementVisible(), I've used a default timeout of 30000. There doesn't seem to be any penalty for larger values.
There may be better answers, but this has worked reasonably well for me so far.
I'm marking this as the answer for now, but am open to changing that if someone has a better strategy.

To Handle Popup message in 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.

Resources