Keep on refreshing the page until certain element to appear? - selenium

I have a scenario like, i want to keep on refreshing the page until some element to appear in the page. Can anyone please help me on the same?
I am using the below code for the same but the page is not refreshing after five second
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
});
Thanks
Sudhansu

Try using the FluentWait class.
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
In that way Selenium will just wait for a certain period of time until certain elements have been loaded.
I hope that will solve your problem so you don't have to refresh the page.
Edited:
As MrTi so friendly points out, the above code will not refresh your page. It will only wait for a certain period of time until certain elements have been loaded. I just thought it might solve the problem, without you having to refresh the page. If that does not solve your problem and you still need to refresh your page, then you need to add driver.navigate().refresh() before the return, like this:
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
driver.navigate().refresh()
return driver.findElement(By.id("foo"));
}
});

Thank you EmilC for your proposal.
It's also posible to declare the Function using java lambda's syntax the following way.
Wait<WebDriver> wait = new FluentWait<WebDriver>(ctx.driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
wait.until((webDriver) -> {
webDriver.navigate().refresh();
return driver.findElement(by);
});

if $all_loaded = true > do something > else > refresh page

Related

Wait to perform two actions - selenium/ java

I'm trying to use Fluent wait to perform two actions as below:
Click on search button
Check the result for the element
Right now I'm trying with the below code and it doesn't seem to work:
public SendMailPage waitForSometime() throws Exception {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofMinutes(2))
.pollingEvery(Duration.ofSeconds(10))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
driver.findElement(By.xpath("//BUTTON[#type='submit'][text()='Search']")).click();
driver.findElement(By.xpath("xpath of the element i'm waiting to find"));
return driver.findElement(By.xpath("xpath of the element i'm waiting to find"));
}
});
element.isDisplayed();
return new SendMailPage();
}
Can someone guide me on how to fix this?
***UPDATED CODE: where waiting for a single element also doesn't work :
public SendMailPage assertMailSubject() throws Exception {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofMinutes(2))
.pollingEvery(Duration.ofSeconds(30))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.xpath("the element that i am waiting for"));
}
}
);
return new SendMailPage();
}
I fixed both the problems:
The code was not working as the NoSuchElementException was from Java util instead of Selenium.
And for performing two actions, I just added by Search key action before the return statement.

How to wait untill a page is dim after clicking a button?

How to wait until a page is dim(loading) after clicking a button? I tried following options but not succeeded yet. I have to capture transaction timings.
1) Implicit Wait
(driver.manage().timeouts().implicitlyWait(20L, TimeUnit.SECONDS);)
2) Explicit Wait
(wait = new WebDriverWait(driver, 200);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//a[#ardbn='z3Btn_TDS_Next']/div/img)[position()<3]")));)
3) One of my own function
public void waitForPageLoaded() {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete"); } };
Wait<WebDriver> wait = new WebDriverWait(driver,30); try { wait.until(expectation); } catch(Throwable error) { fail("Timeout waiting for Page Load Request to complete."); } }
Wait till invisibility of Loading box.
Suppose locator/id/xpath of Loading box is id = loader, Then
By locator = By.id("loader");
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(timeOutInSeconds, TimeUnit.SECONDS)
.pollingEvery(pollingIntervalInSeconds, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator));

How to use clickandwait in Selenium Webdriver using Java?

I am trying to click on the object, to show the list of value pop-up.
I used the following script, but unable to populate the list value pop-up.
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
Thread.sleep(1000L);
Is there any other way to click and wait for the object?
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
There are other conditions like visibilityOf so choose the one which suits you most - documentation here.
String mainWindowHandle = driver.getWindowHandle();
System.out.println(mainWindowHandle);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(OR.getProperty(Object)));
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
PageUtil.sleep(3000);
Set<String> s1 = driver.getWindowHandles();
Iterator<String> ite = s1.iterator();
while (ite.hasNext()) {
String popupHandle = ite.next().toString();
System.out.println(popupHandle + " Present Pop Up window name");
if (!popupHandle.contains(mainWindowHandle)) {
driver.switchTo().window(popupHandle);
}
}
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
Driver.findElement(By.id("yourId")).click();
driver.switchTo().window(mainWindowHandle);
After clicking you can wait using FluentWait,
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
refer this for more info
I'm not quite familiar with java syntax, but I'll give you php code and you can write similar. The idea is to find HTML element by tag and get it's id BEFORE YOU CLICK. Then AFTER THE CLICK wait for the id to change.
It looks like this:
class MySeleniumCondition extends WebDriverExpectedCondition{
public static function htmlElementIdIsNot($htmlElementId) {
return new WebDriverExpectedCondition(
function ($driver) use ($htmlElementId) {
$htmlElement = $driver->findElement(WebDriverBy::tagName('html'));
return $htmlElementId != $htmlElement->getId();
}
);
}
}
// .............. somehere in a class:
public function waitForNewPage($oldHtmlElementId, $time = 10){
try{
$this->driver->wait($time)->until(
MySeleniumCondition::htmlElementIdIsNot(
$oldHtmlElementId
)
);
return true;
}catch(TimeOutException $e){
return false;
}
}
// use this only when you are sure the page will reload
public function clickAndWait(WebDriverBy $locator, $time = 10){
$webElement = $this->driver->findElement($locator);
$oldHtmlElement = $driver->findElement(WebDriverBy::tagName('html'));
$oldHtmlElementId = $oldHtmlElement->getId();
$webElement->click();
$this->waitForNewPage($oldHtmlElementId, $time);
return true;
}

webdriver implicitWait not working as expected

In webdriver code if i use thread.sleep(20000). It's waiting for 20 seconds, and my code also works fine.
To archive the same if i use implicit wait like
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
It's not waiting forcefully for 20 seconds and goes to next steps just in 3 to 4 seconds. and page still loading.
This is wired situation as i am using fluent wait to find some elements. if the elements still loading on the page it does not show error and make the test passed.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(50, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("jxxx"));
}
});
But if i say wrong id it waits for 50 seconds but other test got passed without clicking.. it is not showing any error.
My Question is how I should avoid Thread.sleep() as other selenium methods are not helping me..
Use below method to wait for a element:
public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
{
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
List<WebElement> elements = driver.findElements(by);
if (elements != null && elements.size() > 0)
return true;
Thread.sleep(250);
}
return false;
}
And below method is to wait for page load:
public void waitForPageLoadingToComplete() throws Exception {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState").equals("complete");
}
};
Wait<WebDriver> wait = new WebDriverWait(driver, 30);
wait.until(expectation);
}
Let's assume you are waiting for a page to load. Then call the 1st method with waiting time and any element which appears after page loading then it will return true, other wise false. Use it like,
waitForElementToBePresent(By.id("Something"), 20000)
The above called function waits until it finds the given element within given duration.
Try any of below code after above method
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
or
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
Update:
public boolean waitForTextFiled(By by, int waitInMilliSeconds, WebDriver wdriver) throws Exception
{
WebDriver driver = wdriver;
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
driver.findElement(By.id("txt")).sendKeys("Something");
String name = driver.findElement(by).getAttribute("value");
if (name != null && !name.equals("")){
return true;
}
Thread.sleep(250);
}
return false;
}
This will try entering text in to the text field till given time in millis. If getAttribute() is not suitable in your case use getText(). If text is enetered then it returns true. Put maximum time that u can wait until.
You might want to try this for an element to become visible on the screen.
new WebDriverWait(10, driver).until(ExpectedConditions.visibilityOfElementLocated(By.id("jxxx")).
In this case, wait time is a maximum of 10 seconds.

Selenium RC : Page is not loading compeletelly

When I run my selenium rc script page is not loading completely because of change in the urls.
Earlier it was working fine when url was something link this
https://testersworld.com/
But now it changed to (updated the URL in the script before run)
https://testersworld.com/#login
Because of which when I run the script browser launches with specified url but fails to displayed login popup.
How to handle this https://testersworld.com/#login which gives login pop after page load. I used all methods of wait.
try this:
driver.manage().deleteAllCookies();
driver.get("https://testersworld.com/");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
or
driver.manage().deleteAllCookies();
driver.get("https://testersworld.com/");
Thread.sleep(1000);
or
select locator on login page (e.g. input login(e-mail ) field):
String cssLocator=..blablabla...;
and use fluentWait mechanism:
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;
fluentWait(By.cssSelector(cssLocator));