Going through Chrome://settings by Selenium - java

I am using Java and Selenium to write a test, I use the code below to get into Chrome:setting
driverChrome.manage().window().maximize();
driverChrome.get("chrome://settings");
But when the page is open I can not find any of its web Elements, for example when I try to find "show advanced setting...." by this code
driverChrome.findElement(By.xpath("//a[#id='advanced-settings-expander']")).click();
it throws an error saying that "no such element: Unable to locate element"
I tried to located other elements, but they all failed. I saw this post here but it did not help.
Find the code below:
driverChrome.manage().window().maximize();
driverChrome.get("chrome://settings");
Thread.sleep(5000);
WebElement w = driverChrome.findElement(By
.xpath("//iframe[#name='settings']"));
driverChrome = driverChrome.switchTo().frame(w);
Thread.sleep(1000);
while (true) {
try {
WebElement we = w.findElement(By
.xpath("//a[text()='Show advanced settings...']"));
if (we.isDisplayed()) {
we.click();
Thread.sleep(1000);
break;
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("=========================");
}
}

I haven't tested this but I took your code snippet and cleaned it up a bit. Try this and see if it works. This should be pretty close.
Once you switch to the IFRAME context, you don't need to reference the IFRAME as you did with w.findElement().
In general, Thread.sleep() is not a good practice. You should prefer to use WebDriverWait with ExpectedConditions. Check the docs for all the different things you can wait for using ExpectedConditions. I used .elementToBeClickable() in my code below. This is perfect since you want to click an element. The .until() returns the element waited for so you can just append .click() on the end of the statement... or you can store the element in a WebElement variable and use it elsewhere.
driverChrome.manage().window().maximize();
driverChrome.get("chrome://settings");
WebElement w = driverChrome.findElement(By.xpath("//iframe[#name='settings']"));
driverChrome = driverChrome.switchTo().frame(w);
WebDriverWait wait = new WebDriverWait(driverChrome, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Show advanced settings...']"))).click();
// alternative example... store returned element and then click on a separate line... or use the variable elsewhere, etc.
// WebElement link = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Show advanced settings...']")));
// link.click();

You will need to identify Shadow roots to interact with a lot of Chromes native pages including the Settings page.
See this Thread on how to work with them properly:
How to interact with the elements within #shadow-root (open) while Clearing Browsing Data of Chrome Browser using cssSelector

Related

Getting error for choosing radio button(Element is not clickable at point (286,871) because another element ) [duplicate]

I see this only in Chrome.
The full error message reads:
"org.openqa.selenium.WebDriverException: Element is not clickable at point (411, 675). Other element would receive the click: ..."
The element that 'would receive the click' is to the side of the element in question, not on top of it and not overlapping it, not moving around the page.
I have tried adding an offset, but that does not work either. The item is on the displayed window without any need for scrolling.
This is caused by following 3 types:
1.The element is not visible to click.
Use Actions or JavascriptExecutor for making it to click.
By Actions:
WebElement element = driver.findElement(By("element_path"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
By JavascriptExecutor:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(250, 0)"); // if the element is on top.
jse.executeScript("scroll(0, 250)"); // if the element is on bottom.
or
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView()", Webelement);
Then click on the element.
2.The page is getting refreshed before it is clicking the element.
For this, make the page to wait for few seconds.
3. The element is clickable but there is a spinner/overlay on top of it
The below code will wait until the overlay disppears
By loadingImage = By.id("loading image ID");
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.invisibilityOfElementLocated(loadingImage));
Then click on the element.
You can also use JavaScript click and scrolling would be not required then.
IJavaScriptExecutor ex = (IJavaScriptExecutor)Driver;
ex.ExecuteScript("arguments[0].click();", elementToClick);
There seems to be a bug in chromedriver for that (the problem is that it's marked as won't fix)
--> GitHub Link
(place a bounty on FreedomSponsors perhaps?)
There's a workaround suggested at comment #27.
Maybe it'll work for you-
I had the same issue, tried all offered solutions but they did not work for me.
eventually I used this:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("var evt = document.createEvent('MouseEvents');" + "evt.initMouseEvent('click',true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0,null);" + "arguments[0].dispatchEvent(evt);", findElement(element));
Hope this helps
Wow, a lot of answers here, and many good ones.
I hope I'll add something to this from my experience.
Well guys, in my case there was a cookie overlay hiding the element occasionally.
Scrolling to the element also works; but in my humble opinion (for my case, not a panacea for everyone) the simplest solution is just to go full screen (I was running my scripts on a 3/4 of the screen window)! So here we go:
driver.manage().window().maximize();
Hope that helps!
You need to use focus or scroll on that element. You also might have to use explict wait.
WebElement firstbutton= driver.findElement(By.xpath("Your Element"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
OR
The element is not clickable because of a Spinner/Overlay on top of it:
By loadingImage = By.id("loading image ID");
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.invisibilityOfElementLocated(loadingImage));
OR
Point p= element.getLocation();
Actions actions = new Actions(driver);
actions.moveToElement(element).movebyoffset(p.x,p.y).click().perform();
OR
If still not work use JavascriptExecutor
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", firstbutton);
I have seen this in the situation when the selenium driven Chrome window was opened too small. The element to be clicked on was out of the viewport and therefore it was failing.
That sounds logical... real user would have to either resize the window or scroll so that it is possible to see the element and in fact click on it.
After instructing the selenium driver to set the window size appropriately this issues went away for me. The webdriver API is decribed here.
I was getting this error when running tests headless with xvfb-run. They were working flawlessly locally. Using chrome, versions of webdriver / chromedriver / chrome / java etc all identical.
The ‘won’t fix’ bug in chromedriver - GitHub Link pointed out by Tony Lâmpada suggested this may be related to what is / isn't visible on the screen.
Help message for xvfb-run shows the following:
-s ARGS --server-args=ARGS arguments (other than server number and
"-nolisten tcp") to pass to the Xvfb server
(default: "-screen 0 640x480x8")
Changing the resolution for xvfb made the error go away:
xvfb-run -s "-screen 0 1280x1024x16" ...
ruby/watir-webdriver/chrome
I use the following trick and seems like it works:
#scroll to myelement
#browser.execute_script "window.scrollTo(#{myelement.element.wd.location[0]},#{myelement.element.wd.location[1]})"
# click myelement
myelement.when_present.fire_event("click")
I, too, wrestled with this problem. Code works fine in FF, fails on Chrome. What I was trying to do was to click a tickbox - if it wasn't in view, I'd scroll to view and then click. Even scrolling into view works in Chrome, only the bottom few pixels of the tickbox wasn't visible so webdriver refused to click on it.
My workaround is this:
WebElement element = _sectorPopup.findElement(...);
((Locatable) element).getCoordinates().inViewPort();
try {
element.click();
} catch (Exception e) {
new Actions(getWebDriver()).sendKeys(Keys.PAGE_DOWN).perform();
element.click();
}
Chrome also has issues with sendKeys, using Actions is sometimes necessary. Obviously, you need to know which direction and how much you need to go so your mileage may vary. But I prefer this to the javascript hack, so I'm posting it here in case someone else will find it useful.
First, try to get the latest Chrome driver and check if it solves the issue.
In my case, it didn't fix the issue. But, the following solution worked for me so far. The following is C# code but you can follow same logic in your specific language. What we do here is,
Step 1: Focus on the element using the Selenium Actions object,
Step 2: Then do a click on the element
Step 3: If there's an exception, then we trigger a javascript "Click" event on the element by executing the javascript script through the Selenium browser driver's "ExecuteScript" method.
You can also skip step 1 and 2 and try only step 3 too. Step 3 would work on it's own but I noticed some strange behavior in one scenario in which step 3, even though it successfully clicked the element, caused unexpected behavior in other parts of my code after clicking the element.
try
{
//Setup the driver and navigate to the web page...
var driver = new ChromeDriver("folder path to the Chrome driver");
driver.Navigate().GoToUrl("UrlToThePage");
//Find the element...
var element = driver.FindElement(By.Id("elementHtmlId"));
//Step 1
new Actions(driver).MoveToElement(element).Perform();
//Step 2
element.Click();
}
catch (Exception)
{
//Step 3
driver.ExecuteScript("document.getElementById('elementHtmlId').click();");
}
I was getting the same issue while running selenium script in python. Here is what I used to click on the element:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).click(element).perform()
When using Protractor this helped me:
var elm = element(by.css('.your-css-class'));
browser.executeScript("arguments[0].scrollIntoView();", elm.getWebElement());
elm.click();
I made this method based on a comment from Tony Lâmpada's answer. It works very well.
def scroll_to(element)
page.execute_script("window.scrollTo(#{element.native.location.x}, #{element.native.location.y})")
end
Today I got the same kind of issue. You don't believe me if i say how i solved the issue.
By maximizing the browser size
Yes, it is a pointer issue that means the size of the browser. For that, you just need to maximize the window size manually or through the code.
I was facing a similar problem whre i have to check two check boxes one after the other.But i was getting the same above error.hence i added wait in between my steps for checking the checkboxes....its working fine and great.here are the steps:-
When I visit /administrator/user_profiles
And I press xpath link "//*[#id='1']"
Then I should see "Please wait for a moment..."
When I wait for 5 seconds
And I press xpath link "//*[#id='2']"
Then I should see "Please wait for a moment..."
When I visit /administrator/user_profiles_updates
Apparently this is the result of a "Won't Fix" bug in the Chrome driver binary.
One solution that worked for me (Our Mileage May Vary) can be found in this Google Group discussion, Comment #3:
https://groups.google.com/forum/?fromgroups=#!topic/selenium-developer-activity/DsZ5wFN52tc
The relevant portion is right here:
I've since worked around the issue by navigating directly to the href of
the parent anchor of the span.
driver.Navigate().GoToUrl(driver.FindElement(By.Id(embeddedSpanIdToClick)).FindElement(By.XPath("..")).GetAttribute("href"));
In my case, I'm using Python, so once I got the desired element, I simply used
driver.get(ViewElm.get_attribute('href'))
I would expect this to only work, however, if the element you are trying to click on is a link...
Re Tony Lâmpada's answer, comment #27 did indeed solve the problem for me, except that it provided Java code and I needed Python. Here's a Python function that scrolls to the element's position and then clicks it.
def scroll_to_and_click(xpath):
element = TestUtil.driver.find_element_by_xpath(xpath)
TestUtil.driver.execute_script('window.scrollTo(0, ' + str(element.location['y']) + ');')
element.click()
This solved the problem for me in Chrome 34.0. It caused no harm in Firefox 28.0 and IE 11; those browsers aren't subject to the problem, but scrolling to the element's position before clicking it still isn't a bad thing.
This might happen if the element changes position while the driver is attempting to click it (I've seen this with IE too). The driver retains the initial position but by the time it actually gets to clicking on it, that position is no longer pointing to that element. The FireFox driver doesn't have this problem BTW, apparently it "clicks" elements programmatically.
Anyway, this can happen when you use animations or simply change the height of elements dynamically (e.g. $("#foo").height(500)). You need to make sure that you only click elements after their height has "settled". I ended up with code that looks like this (C# bindings):
if (!(driver is FirefoxDriver))
{
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(
d => d.FindElement(By.Id(someDynamicDiv)).Size.Height > initialSize);
}
In case of an animation or any other factor you can't easily query for, you can utilize a "generic" method that waits for the element to be stationary:
var prevLocation = new Point(Int32.MinValue, Int32.MinValue);
int stationaryCount = 0;
int desiredStationarySamples = 6; //3 seconds in total since the default interval is 500ms
return new WebDriverWait(driver, timeout).Until(d =>
{
var e = driver.FindElement(By.Id(someId));
if (e.Location == prevLocation)
{
stationaryCount++;
return stationaryCount == desiredStationarySamples;
}
prevLocation = e.Location;
stationaryCount = 0;
return false;
});
I met this because a loading dialog cover on this element. I simplely solve it by add a waiting before working with the this element.
try {
Thread.sleep((int) (3000));
} catch (InterruptedException e) {
//
e.printStackTrace();
}
Hope this help!
Explanation of error message:
The error message simply says, that the element you want to click on is present, but it is not visible. It could be covered by something or temporary not visible.
There could be many reasons why the element is not visible in the moment of the test. Please re-analyse your page and find proper solution for your case.
Solution for particular case:
In my case, this error occures, when a tooltip of the screen element i just clicked on, was poping over the element I wanted to click next. Defocus was a solution I needed.
Quick solution how to defocus would be to click to some other element in another part of the screen which does "nothing" resp. nothing happens after a click action.
Proper solution would be to call element.blur() on the element poping the tooltip, which would make the tooltip disapear.
The reason for this error is that the element that you are trying to click is not in the viewport (region seen by the user) of the browser. So the way to overcome this is by scrolling to the desired element first and then performing the click.
Javascript:
async scrollTo (webElement) {
await this.driver.executeScript('arguments[0].scrollIntoView(true)', webElement)
await this.driver.executeScript('window.scrollBy(0,-150)')
}
Java:
public void scrollTo (WebElement e) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript('arguments[0].scrollIntoView(true)', e)
js.executeAsyncScript('window.scrollBy(0,-150)')
}
I was facing the same problem with clj-webdriver (clojure port of Selenium). I just translated the previous solution to clojure for convenience. You can call this function before doing click or whatever to avoid that problem.
(defn scrollTo
"Scrolls to the position of the given css selector if found"
[q]
(if (exists? q)
(let [ loc (location-once-visible q) jscript (str "window.scrollTo(" (:x loc) "," (:y loc) ")") ]
(execute-script jscript))))
Maybe it's not really clean solution but it works:
try:
el.click()
except WebDriverException as e:
if 'Element is not clickable at point' in e.msg:
self.browser.execute_script(
'$("{sel}").click()'.format(sel=el_selector)
)
else:
raise
I was getting this bug because I tested a hover and then needed to click on the link underneath the tooltip. The solution was to add page.find('.sp-logo').hover before click_link to get the tooltip out of the way.
It's funny, all the time I spent looking at the various responses, no one had tried the obvious, which of course, I hadn't either. If your page has the same id used multiple times, as mine did, ("newButton",) and the one you want is not the first one found, then you will in all likelihood get this error. The easiest thing to do (C#):
var testIt = driver.FindElements(By.Id("newButton"));
Note it's FindElements, not FindElement.
And then test to see how many results came back from the retrieval. If it's the second one, you can then use:
testit[1].Click();
Or get whomever reused ids to fix them.
After testing all mentioned suggestions, nothing worked. I made this code. It works, but is not beautiful
public void click(WebElement element) {
//https://code.google.com/p/selenium/issues/detail?id=2766 (fix)
while(true){
try{
element.click();
break;
}catch (Throwable e){
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
public void click(String css) {
//https://code.google.com/p/selenium/issues/detail?id=2766 (fix)
while(true){
try{
driver.findElement(By.cssSelector(css)).click();
break;
}catch (Throwable e){
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
I do a kind of brute force of clicks and it works for me.
try:
elem.click()
except:
print "failed to click"
size = elem.size
mid_of_y = int(size["height"])/2
stepts_to_do_to_left = int(size["width"])
while stepts_to_do_to_left > 0:
try:
print stepts_to_do_to_left, mid_of_y
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(elem, mid_of_y, stepts_to_do_to_left)
action.click()
action.perform()
print "DONE CLICK"
break
except:
pass
If you have jQuery loaded on the page, you can execute the following javascript command:
"$('#" + element_id + "').click()"
Example using python executor:
driver.execute_script("$('#%s').click()" % element_id)
Try to maximize the browser when you are working with resolutions greater than 1024x768.
driver.manage().window().maximize();

How to handle StaleElementReferenceException

I am working for a mouse hover and i want to test all the links working condition by clicking each and every link using for loop.In my program the iteration is going once and for the next iteration it is not working and showing the "StaleElementReferenceException"..........
Please do modification in the code if required....
public static void main(String[] args) throws IOException
{
WebDriver driver = new FirefoxDriver();
Autoit.Authenti(driver);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.get("http://staging.zenrays.com");
Actions a1=new Actions(driver);
WebElement cl=driver.findElement(By.xpath(".//*[#id='menu-450-2']/a"));
a1.moveToElement(cl).perform();
WebDriverWait wait =new WebDriverWait(driver, 30);
List<WebElement> links=driver.findElements(By.xpath("//a[contains(#class,'sf-depth-2')]"));
for(int i=0;i<=links.size()-1;i++)
{
links.get(i).click();
driver.navigate().back();
}
}
}
Understand one fundamental thing: staleElementReferenceException, by it's name suggests that the reference to your elements on the page is stale (lost). You just have to refer to those elements again, if they are available, which is apt in this case as the page has been refreshed. Do 2 things:
once the page is refreshed (when you navigate back), use an explicit wait until an element you expect is visible
Then, newly refer to your elements(xpath locator that you have used) you wanna work with again
As a clean and elegant code use try-catch block in these scenarios
I'm not gonna give you the code directly:)Try it and come back with your code.
Refer here
for it's clear explanation of possible scenarios for this particular exception
One more thing: Your for loop gives IndexOutOfBoundsException. Modify that as well
You can use following modification in your code:-
List<WebElement> links=driver.findElements(By.xpath("//a[contains(#class,'sf-depth-2')]"));
for(int i=0;i<links.size();i++)
{
List<WebElement> allLinks=driver.findElements(By.xpath("//a[contains(#class,'sf-depth-2')]"));
allLinks.get(i).click();
driver.navigate().back();
}

Selenium Driver (Chrome) Can't Find Dropdown on hover Element

I'm using the Selenium Chrome Driver to run a couple tests on various site environments, however, when attempting to use an element from a hover drop down menu, I can't seem to reliably select the elements. This works 100% of the time when I'm debugging, but when I run it without an attached debugger it fails about 2/3rds of the time. Here is the code:
private void prepWindow(WebDriver driver, boolean isNightly, String toClick) {
WebDriverWait wait = new WebDriverWait(driver, 300);
try {
if (isNightly) {
WebElement nightlyPopup = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(BOWebElements.nightlyPopup)));
nightlyPopup.click();
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Nightly popup has changed names again.", "Error", JOptionPane.ERROR_MESSAGE);
}
WebElement user = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Users")));
Actions action = new Actions(driver);
action.moveToElement(user).build().perform(); //Makes hover drop down appear
driver.findElement(By.id(toClick)).click(); //Should click element that is only visible when hover drop down is open
}
I should also note that the same code above works perfectly without using a debugger on a coworker's computer, but not my own.
I would like to use XPath but unfortunately the elements of the drop down aren't actually children of the link I have to hover over to open the drop down. If I try to navigate directly to the element using the XPath, it gives me an error saying the XPath isn't valid. Here is one of the potential XPaths:
//html/body/#outTemplateId/#preambleFormId/#globalNavigation/#navBGC/#navBGCmainMM/ul/li/ul/table/tbody/tr/td/ul.ui-menu-list.ui-helper-reset/li.ui-menuitem.ui-widget.ui-corner-all/a#fleetUsersId2.ui-menuitem-link.ui-corner-all.submenu
How can I make the behavior consistent?
Chain your actions together to better emulate the actions that a user would take:
action.moveToElement(user).moveToElement(driver.findElement(By.id(toClick))).click().build().perform();
Check out this question for more details:
https://stackoverflow.com/a/17294390/3537915

Selenium click not always working

I have some tests which click on a tab, however the click is not always performed.
The xpath is correct as most of the times the test works
It is not a timing issue as I ve used thread.sleep() and other methods to ensure that the element is visible before clicking
The test believes that it is performing the click as it is not throwing an ElementNotFoundException or any other exceptions when 'performing' the click. The test fails later on after the click since the tab content would not have changed.
Further Info
I am using Selenium 2.44.0 to implement tests in Java which run on Chrome 44.0.2403.107 m.
Is there something else that I can do or could this be an issue with selenium?
There are several things you can try:
an Explicit elementToBeClickable Wait:
WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("myid")));
button.click()
move to element before making a click:
Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();
make the click via javascript:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", button);
you can go with linkText if the tab name contains any unique string. And make sure your tab is not dynamic. It should be visible in source code(manual source code(ctrl+u)).
The following method work for me
WebElement button = SeleniumTools.findVisibleElement(By.cssSelector("#cssid"));
Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();
I have a similar problem. Tried all solutions from the top answer. Sometimes they work, sometimes don't.
But running code in an infinite loop works always.
For example, we need to click on element-two which is not visible until element-one is clicked.
WebDriverWait wait = new WebDriverWait(webDriver, 10);
while (true){
try {
WebElement elementOne =
wait.until(ExpectedConditions.elementToBeClickable(By.id("element-one")));
elementOne.click();
WebElement elementTwo =
wait.until(ExpectedConditions.elementToBeClickable(By.id("element-two")));
elementTwo.click();
break;
} catch (Exception e){
//log
}
}
I have a similar problem. Here is my solution:
table_button = driver.find_element(By.XPATH, insert your xpath)
try:
WebDriverWait(driver, 15).until(EC.element_to_be_clickable(table_button)).click()
except WebDriverException as e:
print('failed')
print(e)
Through code above, you can find the error message if your button is not clickable.
For example, my error message is 'nosuchelement' and 'clcik is not clickable', then I got back to check the table_button.accessible_name, found it print a 'null' value, so that means my XPATH is incorrect.

How to handle "StaleElementReferenceException" using Chrome browser

I am testing the newly built framework, and am often encountering org.openqa.selenium.StaleElementReferenceException while working in the Chrome browser. Could there be an issue with the framework design?
There are no issues when I run my tests in other browsers. I tried many types of custom waits that catch the StaleElementReferenceException and then loops to find the element, but no luck.
Has anyone faced a similar issue and found a solution?
Chrome version: 38.0.2125.111
Selenium version: 2.43.1
public WebElement waitTill(By by){
WebElement ele = null;
for(int i=0; i<15; i++){
try {
ele = driver.findElement(by);
if(ele==null)
Thread.sleep(2000); //in last attempt used thread...we wont use this in actual practice
else
break;
} catch (NoSuchElementException | InterruptedException e) {
System.out.println(e.getMessage());
}
}
return ele;
}
public WebElement getElement(String loc) {
String locator = initUtils.ORProp.getProperty(loc);
WebElement element = null;
try{
By by = getBy(locator);
element = waitTill(by);
}catch(NoSuchElementException e){
System.out.println(e.getMessage());
}catch(StaleElementReferenceException e){
By by = getBy(locator);
element = waitTill(by);
}
return element;
}
This sort of error is caused by the webpage changing in between times the element is checked.
This exception is mostly caused by bad tests I am afraid to say. A few things to check for are:
Make sure that you are giving the page time to load when you go to it
before you start interacting with it, even if you think it has
finished loading it may still be waiting for something in the
background and when it arrives the page changes.
Make sure that if you interact with any element that changes the page
make sure you again wait for the page to change and any html requests
to process.
These two things may be the cause of most of your problems, I would recommend using a ajax that uses jQuery ajax start and stop in order to make sure that the page is loaded before modifying it. What you need to remember is selenium is so much faster than a user could possibly interact with the page and you need to handle that by increasing checks.
I would also recommend checking whether an element is on the page and that it is visible before even trying to interact with it.
In a worse case senario you could use a try and catch block to check for the element but if you make sure the page is not changing then you shouldnt get the exception. It does differ between browsers due to browser speed and webdriver speed.
Some of the code I use is:
var finished = false;
function ready() {
if (finished == true) {
$( "#main" ).addClass("ready");
}
}
$( document ).ajaxStart(function() {
$( "#main" ).removeClass("ready");
finished = false;
});
$( document ).ajaxStop(function() {
finished = true;
window.setTimeout(ready,500);
});'
This checks that the page is fully loaded and no requests are pending, I just execute this once the browser is open, I then can just check whether the class is present and if it is I am ready to go. I call the same check whenever the page changes as well.
Programmatically, I might use an explicit wait with ExpectedConditions instead of Thread.sleep():
public WebElement element2Click (By by){
WebElement myClickableElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.elementToBeClickable(by));
return myClickableElement;
}
But if this does not solve the problem and your automated test program is quite stable across the other browsers, it could be that the web page or webapp you are testing does not support Chrome, and you may be seeing StaleElementReferenceException errors because the HTTP messages are not communicating properly. In this case, check out the HTTP traffic on the browser.

Categories