Every Java code export from selenium ide will have this method..But it is the same with method for iselementpresent because I cant figured out how to use it:
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
What need to be put exactly in the try code?
The above method is not same as isElementPresent(). The closeAlertAndGetItsText() method is for handling alert boxes in your web application.
Where ever you need to handle the alert boxes in your web application, you can simply make a call to this closeAlertAndGetItsText() method. closeAlertAndGetItsText() method will click OK on the alert box and alert.getText() will provide you the text that was present in the alert box.
isElementPresent() is a method, which you will call when you need to find whether a particular element is present in the webpage or not. There are many implementations of isElementPresent() Find below some of them.
private boolean isElementPresent(WebDriver driver, String id) {
try {
driver.getWrappedDriver().findElement(By.id(id));
return true;
} catch (Exception e) {
return false;
}
}
private boolean isElementPresent(WebDriver driver, String classname) {
try {
driver.findElements(By.className("someclass")).size() > 0;
return true;
} catch (Exception e) {
return false;
}
}
Related
How to verify whether file downloading is completed before closing my Selenium web driver in JAVA.
I have written a Selenium code to download 2 files to my desired folder location. However I close the browser instantly after clicking on the 2 links, which given me the downloaded files as temporary files or with an invalid extension. I used Thread.sleep method after clicking on the each of the two links before closing the web driver and it is now working fine.
I need to know whether there is an optimum method to check whether download is completed or not before closing the web driver using explicit method or any other way rather setting a pre-defined time using the Thread.sleep() method.
Here is part of the source code (JAVA, Selenium and Testng) which is relevant to this question.
// Text file download
#Test(priority=2)
public void txtFileDownloadTest() {
fileDownloadPage.clickTxtFileLink();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Java file download
#Test(priority=3)
public void javaFileDownloadTest() {
fileDownloadPage.clickJavaFileLink();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#AfterClass
public void setDown() {
closeUp();
}
There is a piece of code I was using to download files. Just change fileName and increase timeout in waitSec(driver, int).
public WebDriverWait waitSec(WebDriver driver, int sec) {
return new WebDriverWait(driver, sec);
}
String fileName = "foo";
String filePathFull = "C:/users/user/downloads/" + fileName + ".csv";
waitSec(driver, 30).until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
if(Files.exists(Paths.get(filePathFull))) {
return true;
}
else {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
return false;
}
});
File exportFile = new File(filePathFull);
if (Files.size(Paths.get(filePathFull)) == 0) {
try {
waitSec(driver, 120).until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
try {
if(Files.size(Paths.get(filePathFull)) > 0) {
return true;
}
else {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
}
catch (IOException e) {
}
return false;
}
});
}
catch (TimeoutException e) {
}
}
There is always a .part file and until download is complete orginial file (csv in my example) has zero size.
In my UI java test framework I have lots of methods that are doing try catch around element actions like click, send keys etc and return true when action is successful and false when any exception occurs. I was wondering is there any smarter way to pass the method as parameter and in that one method surround that code with try catch statement. So that code could be simpler and cleaner to read (may be Java 8 functional interfaces).
public boolean expandPanel(String panelHeading) {
boolean panelFound = false;
try {
getElement(PanelHeadings.fromString(panelHeading)).click();
panelFound = true;
} catch (Exception e) {
panelFound = false;
}
return panelFound;
}
I did try creating an actions class and defining different methods for click, sendKeys etc. But is there a way if i can just have one try catch method and pass code or behaviour to that method.
public boolean expandPanel(String panelHeading) {
return actions.click(getElement(PanelHeadings.fromString(panelHeading)));
}
public class WebElementActions {
public Boolean click(WebElement element) {
try {
element.click();
return true;
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
}
You could do something like
public boolean executeSafely(Runnable action) {
try {
action.run();
return true;
} catch (Exception x) {
return false;
}
}
And then call it with return executeSafely(element::click).
I tried the following solutions to Verify that the button is not displayed for a particular user-group.None of the solutions work. I get a no such element exception with the codes.
Please let me know if there is anything else i can try.
try {
boolean btnPresence = driver.findElement(By.linkText("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed();
}
catch (org.openqa.selenium.NoSuchElementException e)
{
return;
}
}
Assert.assertTrue(driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed());
if (driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed()) {
System.out.println("Fail! Submit button is displayed for a CMS Admin on the ORC TA Form.");}
else {
System.out.println("Pass!!- Submit Button is not displayed for CMS Admin on the ORC TA Form");
}
boolean elePresent = driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed();
boolean elePresent = driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).isDisplayed();
boolean exist = driver.findElement(By.xpath("/html/body/div/div/div/main/div[2]/div[2]/div/form/button")).size() == 0;
You can check if the element exists or not:
public boolean existsElement_byXpath(String xpath) {
try {
driver.findElement(By.xpath(xpath));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
I want to write a reusable method to identify whether the web Element is Present or not.
This method needs to accept e different locators like xpath, id, class name.
Here is the code snipped I tried, but not worked for the line.
if(Obj.isDisplayed())
public static boolean isElementPresent(WebDriver driver, WebElement Obj)
{
boolean result = false;
try
{
// if(Obj.isDisplayed())
if(driver.findElement(By.id("username")) != null)
{
System.out.println("WEBELEMENT Username FOUND");
result = true;
}
else
{
result = false;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
Below method returns true in case element present.
public boolean isElementPresent(WebDriver driver,By locator){
if(driver.findElements(locator).size()!=0){
//Element present
return true;
}
else{
//Element not present
return false;
}
}
Example:
isElementPresent(By.id("test"));
isElementPresent(By.xpath("//test1"));
For your case solution will be Try/Catch:
public boolean isElementPresent(WebElement element) {
try {
element.getText();
return true;
} catch (NoSuchElementException e) {
return false;
}
If element not exists on the page then element.getText() will throw NosuchElementException, method will catch this exception and returns false.
Try it and let me know if it works for you.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
selenium 2.4.0, how to check for presence of an alert
I am using the following code to close the alert window :
Alert alert3 = driver.switchTo().alert();
alert3.dismiss();
The alert appears a few seconds after the opening of the main window.
How can I wait and check if alert appears ?
No default method for waiting for alert.
but, you can write your own method something like this.
waitForAlert(WebDriver driver)
{
int i=0;
while(i++<5)
{
try
{
Alert alert = driver.switchTo().alert();
break;
}
catch(NoAlertPresentException e)
{
Thread.sleep(1000);
continue;
}
}
}
public boolean isAlertPresent() {
boolean presentFlag = false;
try {
// Check the presence of alert
Alert alert = driver.switchTo().alert();
// Alert present; set the flag
presentFlag = true;
// if present consume the alert
alert.accept();
} catch (NoAlertPresentException ex) {
// Alert not present
ex.printStackTrace();
}
return presentFlag;
}