When i try to run my scripts and call this method, when i enter URL into address bar, loading starts and loading take much time,
but sometime when refresh page page proper loaded on the spot so please help me out.
How can i handle this issue in automation.
public static MainPage LaunchBrowserAndLogin(String currentScriptName, String LoginUser) throws Throwable {
try {
killprocess();
LaunchBrowser();
String siteUrl = null;
if (excelSiteURL != null) {
if (excelSiteURL.equalsIgnoreCase("")) {
siteUrl = CONFIG.getProperty("siteName");
}else{
if (excelSiteURL.contains("SiteName")) {
siteUrl=excelSiteURL;
}
}
} else {
siteUrl = CONFIG.getProperty("SiteName");
}
driver.get("https://QA.YYYY.com/ABC9/#/login");
System.out.println("URL for Login: "+siteUrl);
CheckErrorPageNotFound();
driver.manage().timeouts().pageLoadTimeout(Long.parseLong(CONFIG.getProperty("pageLoadTime")), TimeUnit.SECONDS);
enterUserID(currentScriptName, LoginUser);
enterPasswd(currentScriptName);
MandatoryFieldSkipErrMsg("~~~~~~ Mandatory Field is skipped, Getting Error: ");
ClickLoginButton();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
}catch(){
DesireScreenshot("AfterClickOnLoginButton");
String stackTrace = Throwables.getStackTraceAsString(t);
String errorMsg = t.getMessage();
errorMsg = "\n\n\n\n Login failed.See screenshot 'LoginFailed' \n\n\n\n" + errorMsg + stackTrace;
Exception c = new Exception(errorMsg);
ErrorUtil.addVerificationFailure(c);
killprocess();
IsBrowserPresentAlready = false;
throw new Exception(errorMsg);
}
return new MainPage(driver);
}
First you need to check whether page is fully loaded or not in that case we will use the below code.
new WebDriverWait(driver, 5).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Then as per your question I believe that some web elements are not properly getting loaded. So what you can do add one more explicit wait and put that wait inside try catch block as shown below.
try
{
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(By.id("Abhishek")));
System.out.println("Completed");
}
catch( TimeoutException e)
{
System.out.println("Reloading");
driver.navigate().refresh();
}
If it is unable to find that element then in the catch block it will refresh the page and in this way you can proceed further.
Note: I could have written the script for you but application url is invalid.
Related
unable to execute code which showing staleElementException, to get rid of this i have tried the following relocating the element locator, webdriverwait,try n catch, and loop concept for which stale element is showing, i have tried all kind of these but still i'am getting stale element exception could anyone help me to execute that code it may help full someone like me who is following this site.
public void verifyToedit() throws Exception {
test = report.startTest("Verify to edit Account no. of LedgerAccount Test");
test.log(LogStatus.INFO, "Test Started" + test.getStartedTime());
ledger = PageFactory.initElements(driver, LedgerAccounts.class);
ledger.CompanySetupClick.click();
Thread.sleep(1000);
ledger.LedgerAccountsClick.click();
Thread.sleep(1000);
s = new Select(ledger.SelectPayrollCategoriesLedger);
List<WebElement> led=s.getOptions();
int ledselectsize=led.size();
for(int i=0;i<ledselectsize;i++) {
WebElement select=led.get(i);
select.click();
Thread.sleep(1500);
int editsize=ledger.EditActionBtnLedger.size();
System.out.println("edit size is: "+editsize);
try {
for(WebElement r:ledger.EditActionBtnLedger) {
r.click();
}
} catch (Exception e) {
for(WebElement r:ledger.EditActionBtnLedgerStale) {
r.click();
}
}
}
}
IT showing exception in this line
for(WebElement r:ledger.EditActionBtnLedgerStale) {
r.click();
How do i identify download is not completed /in progress ? because i want to close web driver after download finished.
WebDriver: Chrome
sample code like this ,assume chrome driver setup is ready.
#Test
public void testDownloadPdf(){
// here is the selenium java code to download pdf.
// when do i perform driver.close();
}
In general, better close the driver in #AfterClass.
If you know the exact file name and expected location, you can use Paths
String file_path_full = "C:\\users\\username\\downloads\\yourpdffile.pdf";
while(Files.notExists(Paths.get(file_path_full))) {Thread.sleep(10000);}
I found this... it work in my case
here i'm using FileUtils.sizeOfDirectory(downloadfolder) it will return size of directory and will check after every 5 sec is the size is equal or not.if file size is equal then download is completed .
private void waitForDownloadFinished() throws Exception {
try {
String path = "/Download/path/";
if (path != null) {
File folder = new File(path);
long size, reSize;
do {
size = FileUtils.sizeOfDirectory(folder);
Thread.sleep(5000);
reSize = FileUtils.sizeOfDirectory(folder);
} while (size != reSize);
System.out.println("Download completed");
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
getWebBrowser().quit();
}
}
I have my simple selenium program that validate if the value search box in the google is equal to hello world but i got this error:
Exception in thread "main"
org.openqa.selenium.NoSuchElementException: no such element: Unable to
locate element: {"method":"name","selector":"q"}....
Here's my complete code
public class SimpleSelenium {
WebDriver driver = null;
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowserInChrome();
ss.getPage();
ss.listenForHelloWorld();
ss.quitPage();
}
private void openBrowserInChrome(){
System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
driver = new ChromeDriver();
}
private void quitPage() {
driver.quit();
}
private void getPage() {
driver.get("http://www.google.com");
}
private void listenForHelloWorld() {
WebElement searchField = driver.findElement(By.name("q"));
int count = 1;
while (count++ < 20) {
if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Do you wait until the page is ready and element displayed?
I've often got this error when the page is still loading. You could add something like
(MochaJS example, pretty much the same API for JAVA tests)
test.it('should check the field existence', function (done) {
let field_by = By.id(ID_OF_THE_FIELD);
driver.wait(until.elementLocated(field_by,
driver.wait(until.elementIsVisible(driver.findElement(field_by)), TIME_TO_WAIT_MS);
done();
});
You wait until the element is visible. If it failed, the timeout of TIME_TO_WAIT_MS will be raised.
The google search bar will never have "hello world" in it because you haven't typed it in?
Also the search field value doesn't seem to update when you type in a search (if you inspect the element using the Console).
If your just learning I would just write a test like this and the click the search button, then confirm the "hello world" text in the search results:
WebElement searchField = driver.findElement(By.name("q"))
searchField.sendKeys("Hello World")
//Add code to click search button
//Add code to assert results on next page
Also I would completely change your listenForHelloWorld() method and use the built in WebDriver ExpectedConditions:
new WebDriverWait(driver, 10)
.until(ExpectedConditions.textToBePresentInElement(searchField, "Hello World"))
This is a simple sign-in script which I am running in Firefox.
What I am trying to do is to print a message if the sign-in is successful or fails.
I gave wrong user/pass to get the error (verified it against the site that it's correct).
The page-title element only displays if user was logged-in successfully. Similarly, the error-msg element only displays if user was not logged-in.
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://www.example.com";
String actualTitle;
// Launch Firefox and direct it to the Base URL
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
// Maximize the browser window
driver.manage().window().maximize();
// Get the actual value of the title
actualTitle = driver.getTitle();
driver.findElement(By.linkText("Signin")).click();
WebElement email = driver.findElement(By.id("email"));
email.click();
email.sendKeys("abc#example.com");
WebElement pass = driver.findElement(By.id("pass"));
pass.click();
pass.sendKeys("abc123456");
driver.findElement(By.id("send2")).click();
// Variables for Dashboard & Error Title
WebElement dashboardTitle = driver.findElement(By.className("page-title"));
WebElement loginFailed = driver.findElement(By.className("error-msg"));
if(loginFailed.getText().contains("Invalid login or password."))
System.out.println("Test passed but login failed.");
else if(dashboardTitle.getText().contains("My Dashboard"))
System.out.println("Logged in successfully.");
else if(dashboardTitle.getText().contains("Account Information"))
System.out.println("Logged in successfully.");
else
System.out.println("You're not logged-in.");
System.out.println("The title of current page is: "+actualTitle);
driver.close();
driver.quit();
User/Pass are not correct so the 'IF' condition should run but in reality it's giving me error that other element (page-title) is not found.
If I remove the other condition (from IF statement) then the script is running without any issue.
I want the script to run and search for both elements and if it finds only one element (which it should be) then it should display it's result instead of giving me the error that other element is not found.
Use the following method to find a web element, this should help you wait and find element, if element not found it will catch the exception and return null or else a WebElement.
public WebElement waitAndGetElement(WebDriver driver, By by, int waitTimeInSeconds) {
try {
return new WebDriverWait(driver, waitTimeInSeconds).until(ExpectedConditions.visibilityOfElementLocated(by));
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
Example:
WebElement loginFailed = waitAndGetElement(driver, By.className("error-msg"), 5);
if(loginFailed != null && loginFailed.getText().contains("Invalid login or password."))
System.out.println("Test passed but login failed.");
Use a try-catch block.
....
....
driver.findElement(By.id("send2")).click();
try {
WebElement dashboardTitle = driver.findElement(By.className("page-title"));
System.out.println("Logged in successfully.");
/* Continue code for correct login credentials
*
*/
} catch(NoSuchElementException e) {
}
try {
WebElement loginFailed = driver.findElement(By.className("error-msg"));
System.out.println("Test passed but login failed.");
/* Continue code for incorrect login credentials
*
*/
} catch(NoSuchElementException e) {
}
System.out.println("The title of current page is: "+actualTitle);
driver.close();
driver.quit();
....
....
Using this code solved my issue:
Boolean exist;
if(exist = driver.findElements(By.className("page-title")).size() == 0){
WebElement errorMessage = driver.findElement(By.className("error-msg"));
if(errorMessage.getText().contains("Invalid login or passwords.")){
System.out.println("Test passed but login failed.");
}
else
System.out.println("error-msg class found but different message in it.");
}
else{
WebElement dashboardTitle = driver.findElement(By.className("page-title"));
if(dashboardTitle.getText().contains("Account Information"))
System.out.println("Logged in successfully.");
else
System.out.println("LOGGED IN");
}
I've written a standalone function for my selenium script so that when I want to interact with an object I first check if it exists, to do this I've already specified things such the method to identify it by and the data to use etc, and have some methods like so: -
public WebElement waitforElement(individualThreadSession threadSesh) {
String IDString = threadSesh.objLocVal; //This will be the string value to use to identify
String IDType = threadSesh.objLocType; //This will be something like "CSS"/"XPATH" etc
WebElement returnedElement = null;
for (int second = 0; second < threadSesh.sessionWait; second++) {
Action tempAction = new Action();
tempAction.simpleWait(1);
try {
if(IDType.toString().equals("CSS")){
if(isElementPresent(By.cssSelector(IDString), threadSesh)){
returnedElement = threadSesh.driver.findElement(By.cssSelector(IDString));
break;
}
}
else if(IDType.toString().equals("XPATH")){
if(isElementPresent(By.xpath(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.xpath(IDString));
break;
}
}
else if(IDType.toString().equals("ID")){
if(isElementPresent(By.id(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.id(IDString));
break;
}
}
else if(IDType.toString().equals("NAME")){
if(isElementPresent(By.name(IDString), threadSesh)){
returnedElement = threadSesh.driver.findElement(By.name(IDString));
break;
}
}
else if(IDType.toString().equals("PARTIALLINKTEXT")){
if(isElementPresent(By.partialLinkText(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.partialLinkText(IDString));
break;
}
}
else if(IDType.toString().equals("LINKTEXT")){
if(isElementPresent(By.linkText(IDString), threadSesh)) {
returnedElement = threadSesh.driver.findElement(By.linkText(IDString));
break;
}
}
} catch (Exception e) {System.out.println("When trying to find the obj error encountered - " + e);}
}
return (returnedElement);
}
and this: -
public boolean isElementPresent(By myObject, individualThreadSession threadSesh) {
try{
System.out.println("actually check!");
if (threadSesh.driver.findElement(myObject).isEnabled() && threadSesh.driver.findElement(myObject).isDisplayed()) {
return true;
} else {
return false;
}
} catch (NoSuchElementException e){
return(false);
}
}
But every time I run this it errors with the below and exits the test: -
Test failed with the following error: - org.openqa.selenium.NoSuchElementException:
Unable to find element with xpath == .//*[#id='main']/div[1]/div[1]/h1/span
Shouldn't this work?
I think it could be because I also have an WebDriverEventListener running which I'm guessing is catching this error and exiting the test etc, is there any way I can stop this eventlistener from listening during this waitforelement process?
If not is there a way I can check if the object is enable and visible or not without it throwing an exception?
The event listener is like so: -
WebDriverEventListener listener = new AbstractWebDriverEventListener() {
#Override
public void onException(Throwable t, WebDriver driver) {
//Add in take screenshot here at some stage!
if(!errorsCaught){
errorsCaught=true;
try{
driver.quit();
}catch(WebDriverException theError){}
System.out.println();
System.out.println(Thread.currentThread().getName() + " has encountered an error ");
individualThreadSession.this.endSession(individualThreadSession.this, t);
}
}
};
More digging reveals that it looks like it is the listener picking up things before the catch does anything with it, so now I need to somehow work out how to get it to ignore the error! Any ideas?
I had failed to spot one key line in my event listener, the #Override! This was causing my listener to pick up all exceptions before any catch's I may have also put in, and my listener will just kill off the session and close the run as it should (even though I don't want it to do something in that case).
To get round this issue as I always go through the same route above to check for an object before interacting with it I can be fairly confident that this object will always be there before trying anything or timeout and exit gracefully.
So I've inserted a basic check like so: -
t.getClass().getSimpleName().toLowerCase().equals("nosuchelementexception")
So if the error is a nosuchelementexception I don't bother doing anything with it and just go back into my loop, simples! :)
If findEelement is unable to find the element you will get a NoSuchElementException. This is expected. Instead, try to use findElements that will return an empty list instead of an exception if no elements are present.
Two ways of solving your problem:
Boolean isPresent = driver.findElements(myObject).size()<0
or
private boolean doesElementExist (myObject) {
try {
driver.findElement(myObject);
} catch (NoSuchElementException e) {
return false;
}
return true;}