Selenium 2: Interrupt a page load - java

I have an issue when clicking on a button with Selenium 2.0b3 Java API with FirefoxDriver. Clicking on the button sends a form to the webserver and then browser goes to a new page as a result of the form submission.
When clicking on an element with element.click(), selenium is waiting for the browser to complete its operations. The browser waits until the page load is finished. But, sometimes the page load takes an enormous amount of time due to some advertisement requests.
How to work around the synchronisation between element.click() and the page load?
EDIT:
As explained in the WebElement javadoc:
Click this element. If this causes a
new page to load, this method will
block until the page has loaded.
Thanks

Try the beta feature only for Firefox listed in the last section of the firefoxdriver wiki page http://code.google.com/p/selenium/wiki/FirefoxDriver
You will need at least version 2.9, I recommend going with the latest 2.18 (2.0b3 is nearly a year old now!)

driver.get() is actually supposed to block until the page has finished loading. However sometimes it doesn't for example if JavaScript continues to load after the main HTML has loaded. In this case you'll sometimes get problems with clicking elements which have not appeared yet. You can either use WebDriverWait() to wait for the element to appear or increase the implicit wait time with:
driver.manage().timeouts().implicitlyWait(X, TimeUnit.SECONDS);
Here is the equivalent using WebDriverWait:
public void waitAndClick(WebDriver driver, By by) {
WebDriverWait wait = new WebDriverWait(driver, 10000);
Function<WebDriver, Boolean> waitForElement = new waitForElement(by);
wait.until(waitForElement);
Actions builder = new Actions(driver);
builder.click(driver.findElement(by)).perform();
}
And the waitForElement class:
public class waitForElement implements Function<WebDriver, Boolean> {
private final By by;
private String text = null;
public waitForElement(By by) {
this.by = by;
}
public waitForElement(By by, String text) {
this.by = by;
this.text = text;
}
#Override
public Boolean apply(WebDriver from) {
if (this.text != null) {
for (WebElement e : from.findElements(this.by)) {
if (e.getText().equals(this.text)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
} else {
try {
from.findElement(this.by);
} catch (Exception e) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
}
}

This is completely untested, but I thought I'd throw it out there for you. I thought that maybe you could work around it by building a custom action.
protected static void maybeAsyncClick(WebElement element, WebDriver driver)
{
Actions builder = new Actions(driver);
Action newClick = builder.moveToElement(element)
.click()
.build();
newClick.perform();
}

Related

Stale Element Reference appears when navigating back to a page, how to write a neat code

I am automating in Java Selenium, without using Page Factory.
I have an Add Candidate Button element that is clicked in two tests. One is straightforward, after entering InviteToCompany page I click this button and proceed. However, another requires me to go past InviteToCompany page, but then use Go Back Arrow to go back to 'InviteToCompany' page and click Add Candidate Button again. This is when StaleElementReferenceException appears.
I have written such a piece of code to deal with this issue, however I am wondering, if there is a cleaner and neater way, than catching exception for second test, to proceed.
public InviteToCompanyPO clickAddCandidateBtn() {
try {
getClickableElement(addCandidateBtn).click();
} catch (StaleElementReferenceException e) {
log.warn("StaleElementReferenceException caught, retrying...", e);
getClickableElement(addCandidateBtn).click();
}
return new InviteToCompanyPO(driver);
}
Before I had to write second test (the one causing staleness), this method simply looked like this:
public InviteToCompanyPO clickAddCandidateBtn() {
getClickableElement(addCandidateBtn).click();
return new InviteToCompanyPO(driver);
}
I tried writing something like this:
public InviteToCompanyPO clickAddCandidateBtn() {
wait
.ignoring(StaleElementReferenceException.class)
.until(ExpectedConditions.elementToBeClickable(addCandidateBtn))
.click();
return new InviteToCompanyPO(driver);
}
but it doesn't work.
I guess you are using a page factory?
Anyway, when you back to the InviteToCompany page and need to click Add Candidate Button again you will need to get that element again.
I mean to pass the locator or By of that element and get the WebElement object again with driver.findElement() method.
This causes by the fact that WebElement is actually a reference (pointer) to the actual Web Element on the page. And when you navigating from the page to other page the references to the objects on the previous page becoming invalid, Stale. When you open the previous page again it is rendered again, so you need to get the references (pointers) to elements on that page again.
Cleaner way You can use a Webdriver wait Like this to click
public void refreshedClick(By by){
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class)
.until(new Predicate<WebDriver>() {
#Override
public boolean apply(#Nullable WebDriver driver) {
driver.findElement(by).click();
return true;
}
});
}
Java 8
public void refreshedClick(By by){
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class)
.until((WebDriver d) -> {
d.findElement(by).click();
return true;
});
}

Selenium WebDriver (JAVA) - Fluent wait seems not to be working HALP

After some time searching for the issue I have I could not encounter any solution. So here I am.
Some background, I am trying to automate the sign up, confirmation and join for a "Live Class" for certain platform.
To do so, you have every 10 minutes a 5 minutes window where you can sign up, then confirm, then wait X time then Join the live class.
But this is just for the first part, where I want to sign up. This is what I did using fluent wait:
public void joinPrivateClass() {
System.out.println("Starting join private class");
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(480))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement signUp = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
WebElement signUpButton = driver.findElement(By.xpath("//*[#id=\"live-class-322102\"]/div[1]/div/div/button"));
if(signUpButton.isDisplayed()){
System.out.println("button is displayed");
} else {
System.out.println("button is not displayed yet");
}
return signUpButton;
}
}); signUp.click();
}
My issue is that after the page is loaded, while the fluentwait "works" I expected to have a "Button is not displayed" every 5 sec until it is and then gets clicked. but while the button is displayed or not I am not getting any message neither the "Button is not displayed" nor "The button is displayed" so I would assume that something is failing in the "wait.until"
Some things to mention, I am not a programmer so sorry if I did something wrong,
Also in my IDE (intelliJ) it marks me the "driver" of this portion of code
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
In "purple" and this "driver" :
public WebElement apply(WebDriver driver)
in GREY if it has anything to do with! thanks for your precious help
Your wait is built with ignoring(NoSuchElementException.class). So as long as the button does not exist, your wait.until(...) will just silently keep failing at the findElement(...) line - it will never make it to the println(...).
Remove the ignoring(...) from your wait, and change your wait.until(...) body to something like:
WebElement signUpButton;
try {
signUpButton = driver.findElement(By.xpath("//*[#id=\"live-class-322102\"]/div[1]/div/div/button"));
System.out.println("button is displayed");
} catch(NoSuchElementException ignored) {
System.out.println("button is not displayed yet");
}
return signUpButton;

Why isn't my click event not working in Selenium?

When clickevent is fired, I want it to redirect/open new page in same tab. The new tab would be '/Waiting', however even after click event is fired, it stays in the same page. While doing manually by going to browser's localhost, it works though. Also, even after 10 secs, it doesn't load.
#Test
public void firstPlayerConnection() {
try {
driver.get(uiPath);
WebElement startGame = driver.findElement(By.id("startGame"));
startGame.click();
WebElement gif = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("loading")));
assertEquals("/Waiting", driver.getCurrentUrl());
} finally {
driver.quit();
}
}
Provide wait explicitly, & if it still does not work then try to use submit() in place of click().
If I'm not mistaken the NoSuchElement exception must be on the startGame.Click() command. To avoid this exception you have to (explicit) wait till this element is clickable.
WebElement startGame = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.elementToBeClickable(By.id("startGame")));

Customwait - Check element is visible/disappear with selenium webdriver (element is in the DOM, but not visible)

I would like to implement a custom wait method which should wait till a loading popup is visible.
This loading popup has its own id = "wait". I use this custom expectedConditions (from Stackoverflow) to check it:
public static ExpectedCondition<Boolean> absenceOfElementLocated(
final WebElement element) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
try {
element.isDisplayed();
return false;
} catch (NoSuchElementException e) {
return true;
} catch (StaleElementReferenceException e) {
return true;
}
}
#Override
public String toString() {
return "element to not being present: " + element.getText();
}
};
}
My script pass on when the loading still visible and I do not know why.
Thanks!
Use ExpectedConditions#invisibilityOfElementLocated(By locator)
You can also use negation -> ExpectedConditions#not(ExpectedCondition condition)
A basic example:
Go to this page: Primefaces - dropdown
There is Submit button on this page, if you click on this button, then Selected message will appear on the screen, then this message will dissapear after a few seconds.
So we will wait in our code for the following events:
the button appears and is clickeable (it cannot be clicked until it is not clickeable)
the message appears and is visible
the message disappears an is not visible
WebDriver driver = new ChromeDriver();
try {
driver.get("https://www.primefaces.org/showcase/ui/ajax/dropdown.xhtml");
final By buttonSubmit = By.xpath("//button[ *[ text() = 'Submit' ]]");
final By message = By.xpath("//span[ text() = 'Selected' ]");
WebDriverWait wait = new WebDriverWait(driver, 50);
long time = System.currentTimeMillis();
wait.until(ExpectedConditions.elementToBeClickable(buttonSubmit)).click();
System.out.println(String.format("Button clicked after %d miliseconds", System.currentTimeMillis() - time));
wait.until(ExpectedConditions.visibilityOfElementLocated(message));
System.out.println(String.format("The message appeared after %d miliseconds", System.currentTimeMillis() - time));
// wait.until(ExpectedConditions.invisibilityOfElementLocated(message));
wait.until(ExpectedConditions.not(ExpectedConditions.visibilityOfElementLocated(message)));
System.out.println(String.format("The message dissapeared after %d miliseconds", System.currentTimeMillis() - time));
} finally {
driver.quit();
}
And a result is:
Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 15827
.....
.....
.....
Button clicked after 153 miliseconds
The message appeared after 791 miliseconds
The message dissapeared after 6924 miliseconds
It's hard to tell why your code isn't working without more of the code. You do have some logic errors in your custom wait but you don't need that custom wait because ExpectedConditions already has visibility and invisibility covered.
Use this to wait for the popup to appear
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.id("wait")));
Use this to wait for the popup to disappear
new WebDriverWait(driver, 10).until(ExpectedConditions.invisibilityOfElementLocated(By.id("wait")));
There are times when a popup is just a container for dynamically loaded content. In these cases, you might wait for the frame of the popup to appear but the contents of the frame are not quite loaded yet so if you try to interact with them, you will get errors. In those cases you will need to wait for an element inside the container to be visible.
Same thing for when a dialog is closing. I've had experiences where I've waited for the dialog container to close but the grey overlay is still up blocking clicks, etc. In those cases I had to wait for the overlay to become invisible.
I would suggest that you spend some time familiarizing yourself with the available methods of ExpectedConditions and save yourself having to write custom waits for things that already exist and don't need to be debugged/tested.

selenium webdriver - wait until google map all tiles loaded

I'm new to selenium and I'm kind of stuck.
I'm automating GWT base application and I need to wait till map tiles are fully loaded before moving to next process.
I'm try to find in google but no luck.
I found something like
public static final void waitTillPageLoad()
{
WebDriverWait wait = new WebDriverWait(LoginTestScript.fd, 40);
wait.until( new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
}
);
}
but, I need to wait untill map tiles loaded not document.readyState
do anyone have idea how can I wait until all map tiles loaded successfully.
Thank you.
You can use the below method:
public boolean checkForPresenceOfElementByXpath(String xpath){
try{
new WebDriverWait(driver, 5)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(xpath)[last()]")));
return true;
}catch(Exception e){
return false;
}
}
Remove the return type and return statements, if you dont want to return the values.

Categories