There are multiple files which should be uploaded and waiting for output. It opens up an AJAX like window during processing. If processing takes too much time, Close button should be clicked on this window and file should be submitted again.
I try to use code below, but doesn't click Close button in 10 seconds.
public void clickOnSendButton() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement webElement;
try {
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
driver.findElement(sendButton).click();
log.info("Processing in progress!");
webElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("button-download")));
} catch (TimeoutException ex) {
webElement = null;
} finally {
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
}
if (webElement == null) {
driver.findElement(popUpClose).click();
TimeUnit.SECONDS.sleep(1);
driver.findElement(sendButton).click();
}
}
Try using 'visibilityOfElementLocated' condition instead of 'presenceOfElementLocated' as below:
webElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("button-download")));
Using the loop:
try {
driver.findElement(By.id("button-submit")).click();
Thread.sleep(3000);//3 seconds
log.info("Processing in progress!");
for(int i=0; i<10;i++){
try{
webElement = driver.findElement(By.className("button-download"));
} catch (Exception e){e.printStackTrace();}
if(webElement.isDisplayed())
break;
else
Thread.sleep(1000);
}
} catch (TimeoutException ex) {ex.printStackTrace();} finally {
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
}
if (!webElement.isDisplayed() ) {
driver.findElement(By.xpath("/html/body/div[4]/div[1]/button/span[1]")).click();
Thread.sleep(2000);
driver.findElement(By.id("button-submit")).click();
}
Related
I have to files out of which the first file contains login details. First file is loginDetailsClass.java and below is the code in the file.
public class loginDetailsClass {
#SuppressWarnings("deprecation")
public static void browserLaunch() {
WebDriver driver;
String baseurl = "https://www.facebook.com/";
System.setProperty("webdriver.chrome.driver","D:\\eclipse-workspace\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
options.addArguments("--disable-infobars");
capabilities.setCapability("chrome.binary","D:\\eclipse-workspace\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
//Login section
try {
Thread.sleep(7000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement usnfield = driver.findElement(By.id("email"));
usnfield.sendKeys("alex");
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement pwdfield = driver.findElement(By.id("pass"));
pwdfield.sendKeys("alex42");
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement lgn_btn = driver.findElement(By.id("u_0_8"));
lgn_btn.click();
}
}
And the second file is facebookClass.java and below is the code in the file.
public class facebookClass {
static WebDriver driver;
#Test(priority = 0)
public static void main(String[] args) {
loginDetailsClass.browserLaunch(); //function called from loginDetailsClass.java page
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
#Test(priority = 1)
public static void searchfriends() {
//Switching to iFrame for locating elements
driver.switchTo().frame(driver.findElement(By.id("contentFrame")));
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
//Searching a friend using friend name field
WebDriverWait wait = new WebDriverWait (driver, 20);
WebElement friendName = wait.until(ExpectedConditions.elementToBeClickable(By.id("txtFriendName")));
friendName.sendKeys("James");
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement clck_Search = driver.findElement(By.id("btnSearch"));
clck_Search.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement select_friend = driver.findElement(By.xpath("//*[#id=\"trFriend_3\"]"));
select_friend.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
//Switching back to main frame from iFrame
driver.switchTo().defaultContent();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
#Test(priority = 2)
public static void logout() {
//Logout
WebElement logout = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[1]/td/div/div[8]/table/tbody/tr/td[2]"));
logout.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
driver.close();
}
}
While executing facebookClass.java, login method is called properly and login is successful. But from public static void searchfriends() method, execution doesn't works further. At the very first days all methods got executed successfully. But from the next day it now working.
This is the snapshot of Login popup :
I'm newbie in Selenium webdriver. I wrote this code to figure out navigate commands but once the browser opens, there is a login popup that is displayed. I tried to close it using classname or xpath but timeout exception occurs.
Do I need to use explicit wait in this case? Could you help me to figure out what the problem is?
public class TestNavigateCommands {
WebDriver driver;
public void invokeBrowser(){
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
ChromeOptions options=new ChromeOptions();
options.addArguments("start-fullscreen");
driver=new ChromeDriver(options);
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
navigateCommands();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void navigateCommands(){
try {
driver.navigate().to("https://www.flipkart.com/");
Thread.sleep(4000);
driver.findElement(By.className("2AkmmA _29YdH8")).click();
//driver.findElement(By.xpath("//*[#class='_2AkmmA _29YdH8']")).click();
driver.findElement(By.xpath("//span[starts-with(text(),'Applicances')]")).click();
driver.findElement(By.xpath("//span[contains(text(),'Microwave Ovens')]")).click();
Thread.sleep(2000);
driver.navigate().back();
Thread.sleep(2000);
driver.navigate().forward();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
TestNavigateCommands test1= new TestNavigateCommands();
test1.invokeBrowser();
}
}
Exception :
[43.366][SEVERE]: Timed out receiving message from renderer: 37.150
[43.373][SEVERE]: Timed out receiving message from renderer: -0.007
org.openqa.selenium.TimeoutException: timeout
Try this code it may help:
public class TestNavigateCommands {
public static void main(String[] args) throws InterruptedException {
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver,50 );
driver.manage().window().maximize();
driver.navigate().to("https://www.flipkart.com/");
driver.findElement(By.xpath("//button[contains(#class,'YdH8')]")).click();
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[#title='Appliances']//span"))));
driver.findElement(By.xpath("//a[#title='Appliances']//span")).click();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestNavigateCommands {
WebDriver driver;
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-fullscreen");
driver = new ChromeDriver(options);
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
navigateCommands();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void navigateCommands() {
try {
driver.navigate().to("https://www.flipkart.com/");
driver.findElement(By.xpath("//div[#class='_3Njdz7']//button[#class='_2AkmmA _29YdH8']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[#title='Appliances']//span"))));
driver.findElement(By.xpath("//a[#title='Appliances']//span")).click();
Thread.sleep(2000);
driver.navigate().back();
driver.navigate().forward();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have a web application where I press submit button until data available on the table.When in my no data are available then submit button hidden.So we can get logic until submitting button hides we will click.And when button, not available we show on success message and load next browser Url.
for (k=0;k>30;k++) {
try {
driver.findElement(By.xpath(".//*[#id='content']/input")).click();
driver.switchTo().alert();
driver.switchTo().alert().accept();
Thread.sleep(20000);
} catch (org.openqa.selenium.NoSuchElementException e){
System.out.println(""+location+" Done");
}
}
Here driver.findElement(By.xpath(".//*[#id='content']/input")).click(); this line click my submit button.And after submit one browser alert shows thats why i accept this. In this loop for (k=0;k>30;k++) Blindly i take 30..Is there any logic or any sugggestion how can i manage this...
You can use existence of the element in a way something like this:-
By by = By.xpath(".//*[#id='content']/input");
List<WebElement> buttons = driver.findElement(by);
while(buttons !=null && !buttons.isEmpty()) {
WebElement yourButton = buttons.get(0); // assuming only and the first element in the list
yourButton.click();
driver.switchTo().alert();
driver.switchTo().alert().accept(); // ideally this should be sufficient
Thread.sleep(20000);
buttons = driver.findElement(by);
}
Below code may help you.
try {
while(driver.findElement(By.xpath(".//*[#id='content']/input")).isDisplayed()){
driver.findElement(By.xpath(".//*[#id='content']/input")).click();
driver.switchTo().alert();
driver.switchTo().alert().accept();
Thread.sleep(20000);
}
}
catch (org.openqa.selenium.NoSuchElementException e){
System.out.println(""+location+" Done");
}
another solution with findElements,
while(driver.findElements(By.xpath(".//*[#id='content']/input")).size()>0)
{
try {
driver.findElement(By.xpath(".//*[#id='content']/input")).click();
driver.switchTo().alert();
driver.switchTo().alert().accept();
Thread.sleep(20000);
}
catch (org.openqa.selenium.NoSuchElementException e){
System.out.println(""+location+" Done");
}
}
Implement below Logic :
public void test() throws InterruptedException
{
WebElement button = driver.findElement(By.xpath(".//*[#id='content']/input"));
while(checkButton(button))
{
button.click();
driver.switchTo().alert().accept();
Thread.sleep(1000);
}
}
public static boolean checkButton(WebElement element)
{
if(element.isDisplayed())
return true;
else
return false;
}
It will click until your element get invisible once it your can perform your action further. Hope this will help.
Simply checked with isDisplayed() to check whether element is displayed or not
WebElement ele=driver.findElement(By.xpath(".//*[#id='content']/input"));
//check element is present or not
try {
if(ele.size()>0){
if(ele.isDisplayed()){
ele.click();
}
}
//switch to alert and perform operation
driver.switchTo().alert();
driver.switchTo().alert().accept();
Thread.sleep(20000);
}
catch (Exception e){
System.out.println(""+location+" Done");
}
Following way I solve my Problem..Hope Its will help to next visitor
do
{
try {
driver.findElement(By.xpath(".//*[#name='yt1']")).click();
driver.switchTo().alert();
driver.switchTo().alert().accept();
Thread.sleep(20000);
driver.switchTo().alert();
driver.switchTo().alert().accept();
Thread.sleep(2000);
driver.navigate().refresh();
}
catch (org.openqa.selenium.NoSuchElementException e){
System.out.println(""+location+" Done");
}
}
while ((driver.findElements(By.xpath(".//*[#class='google_data_save']")).size()>0));
My problem is I have customWaitMethods such as:
public void waitForLoading(WebElement loadingElement, WebElement errorElement) {
long timeOut = Long.parseLong(PropertyReader.getInstance().getProperty("DEFAULT_TIME_OUT"));
try {
WebDriverWait wait = new WebDriverWait(DriverFactory.getInstance().getDriver(), timeOut);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id(loadingElement.toString())));
if (errorElement.isDisplayed()) {
throw new TestException();
}
} catch (TimeoutException e) {
System.out.println("Timed out after default time out");
} catch (TestException e) {
System.out.println("Unexpected error occurred, environment error");
e.printStackTrace();
}
}
I need some generic customWait methods. I do a search, but several cases need to be handled. Error msg appear -> fail the test. wait for the loading content, and it disappeared, -> check the search result.
How can I extend this code if I would like to check continuously some error_message element appears as well and in this case I would throw an exception? So independently I can handle the timeout exception and the other, error msg?
This sript is failing because of the IF. ErrorElement does not appear on the page, ---> nosuchelementException
You can catch different Exceptions as you see fit. In your case, you want to catch the TimeoutException to handle time outs. Then catch a different type of exception to handle the error message:
public void waitForLoading() {
long timeOut = Long.parseLong(...);
try {
WebDriverWait wait = new WebDriverWait(...);
wait.until(ExpectedConditions.invisibilityOfElementLocated(...));
if (<error-message-appears>) {
throw new CustomErrorMessageAppearedException();
}
} catch (TimeoutException e) {
System.out.println("Timed out after...");
} catch (CustomErrorMessageAppearedException e) {
// handle error message
}
}
The easiest approach I see is:
public void waitForLoading() {
long timeOut = Long.parseLong(PropertyReader.getInstance().getProperty("DEFAULT_TIME_OUT"));
try {
WebDriverWait wait = new WebDriverWait(DriverFactory.getInstance().getDriver(), timeOut);
if (!wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("wait_element")));)
{
throw new NoSuchElementException();
}
} catch (TimeOutException e) {
System.out.println("Timed out after " + timeOut + "seconds waiting for loading the results.");
}
}
I'm having a problem in my script. I'm using Selenium WebDriver to drive a webpage, but i'm getting ElementNotFound exceptions quite regularly. The page takes a second or two to load.
My code is the following:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
try
{
WebElement username = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='gwt-TextBox']")));
username.sendKeys(usernameParm);
}
catch (Exception e) {
e.printStackTrace();
}
The exception still gets thrown after a second or so. Then if i test it by running the following:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
try
{
WebElement username = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='gwt-TextBox1']")));
username.sendKeys(usernameParm);
}
catch (Exception e) {
e.printStackTrace();
}
Knowing that TexBox1 doesn't exist, then it throws the same exception. It doesn't appear to be waiting. In the second instance i would expect it to time out, and not throw ElementNotFoundException.
My implementation is probably wrong.
Checkout my post on this topic: https://iamalittletester.wordpress.com/2016/05/11/selenium-how-to-wait-for-an-element-to-be-displayed-not-displayed/. There are code snippets there. Basically my suggestion is not to use FluentWait, but instead:
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
ExpectedCondition elementIsDisplayed = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver arg0) {
try {
webElement.isDisplayed();
return true;
}
catch (NoSuchElementException e ) {
return false;
}
catch (StaleElementReferenceException f) {
return false;
}
}
};
wait.until(elementIsDisplayed);
Define TIMEOUT with whatever timeout value seems ok for you (i believe you said 10 seconds in your initial issue).
Yes, i'm answering my own question. Figured out what the problem was.
I had imported java.lang.util.NoSuchElementException
I had told FluentWait to ignore NoSuchElementException
What was actually being thrown was org.openqa.selenium.NoSuchElementException
Once i changed it, it seems to work just fine.
Before i figured this out, i also implemented this:
for (int i = 0; i< 10; i++){
if (B_Username){
break;
} else {
try {
WebElement username = driver.findElement(By.xpath("//*[#class='gwt-TextBox']"));
B_Username = true;
username.sendKeys(usernameParm);
} catch (NoSuchElementException e) {
System.out.println("Caught exception while locating the username textbox");
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException ee) {
System.out.println("Somthing happened while the thread was sleeping");
}
}
}
}
which worked fine as well.
Maybe this will help someone else another time.
Thanks to everyone who answered.