Exiting a for loop via try/catch - java

following is a portion of my code
if(search_result.contains(num_per_page_str)) { // if num item per page is => 24,
for(int item = 1 ; item <= num_per_page_int ; item++ ) { //interate over the current page
Thread.sleep(3000);
try {//if display vertical + horizontal
WebElement url = driver.findElement(By.linkText(item_desc)); // get the URL via element
String item_URL = url.getAttribute("href");
System.out.println("Item URL = " + item_URL);
getPrice(driver, item_URL);
} //try
catch (Exception e) { //if display vertical only
WebElement url = driver.findElement(By.linkText(item_desc)); // get the URL via element
String item_URL = url.getAttribute("href");
System.out.println("Item URL = " + item_URL);
getPrice(driver, item_URL);
} //catch
} // for int item = 1
} //if search result
else { //if items per page < 24
}//else
Once in the try/catch branch, upon reaching getPrice(driver, item_URL); , I expect it to call the getPrice function together with the arguements.
However, what I am getting now is upon executing the calling of the getPrice() function, it did not exit the for loop and re-iterates the loop.
Am I doing anything wrong in my code that blocks the exiting of for loop ? Thanks

Add a break after calling getPrive, like:
for(int item = 1 ; item <= num_per_page_int ; item++ ) { //interate over the current page
Thread.sleep(3000);
try {//if display vertical + horizontal
WebElement url = driver.findElement(By.linkText(item_desc)); // get the URL via element
String item_URL = url.getAttribute("href");
System.out.println("Item URL = " + item_URL);
getPrice(driver, item_URL);
break;
} //try
catch (Exception e) { //if display vertical only
WebElement url = driver.findElement(By.linkText(item_desc)); // get the URL via element
String item_URL = url.getAttribute("href");
System.out.println("Item URL = " + item_URL);
getPrice(driver, item_URL);
break;
} //catch
} // for int item = 1

Related

How to check header menu where first menu is mega menu and other are normal in selenium with java

I have a header menu. Where 5 menus are available. First menu have sub menus on hover and other menus are normal. Now when I try to check all menus then I am not able to get menus link after first menu. In this code, I got all links of sub menus, but links from second menus are not getting. It is again getting again links of sub menus instead of next menu. For example I got correct value for (i=0) but when I move to (i=1) then it gets sub menus link, but I want next menu link instead. If I try with menuLink then I got only menu text but URLs are not getting. Here is my code:
//To get links of header
WebElement menu = driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[3]/div/div/div[1]/div/div[2]"));
List<WebElement> menuLink = menu.findElements(By.tagName("li"));
int headerLink = menuLink.size();
System.out.println("Total links in header menu are " +headerLink);
List<WebElement> clickLink = menu.findElements(By.tagName("a"));
String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
//use this for click on sub menus
String clicklnk1 = Keys.chord(Keys.CONTROL,Keys.ENTER);
// loop for clicks and verify header links
for (int i=0; i<headerLink; i++)
{
//for get menu links data
String linkname = menuLink.get(i).getText();
String anchorlink = clickLink.get(i).getAttribute("href");
System.out.println((i+1)+". Link text is " +linkname +" and Link is " + anchorlink);
// if condition for enter hover
if (linkname.contains("HOME") )
{
//hover on home menu
WebElement home = driver.findElement(By.className("sm_megamenu_title"));
Actions action = new Actions(driver);
action.moveToElement(home).perform();
Thread.sleep(2000);
// get sub menus
WebElement megaMenu = driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[3]/div/div/div[1]/div/div[2]/nav/div/div/ul/li[1]/div"));
List<WebElement> link = megaMenu.findElements(By.tagName("a"));
int anchor = link.size();
System.out.println("Total found link in Home menu are " +anchor);
//loop for verify sub menus
for (int j=0; j<anchor; j++)
{
//hover on home menu
WebElement home1 = driver.findElement(By.className("sm_megamenu_title"));
Actions action1 = new Actions(driver);
action1.moveToElement(home1).perform();
Thread.sleep(2000);
//get data of sub menu links
String linkname1 = link.get(j).getText();
String anchorlink1 = link.get(j).getAttribute("href");
System.out.println("1-"+(j+1)+". Link text is " +linkname1 +" and Link is " + anchorlink1);
//IF condition to check that link is available or not and click
if (anchorlink1.contains("#") )
{
System.out.println("Link not found");
continue;
}
else {
link.get(j).sendKeys(clicklnk1);
Thread.sleep(2000L);
}
//To handle windows
Set<String> handles1 = driver.getWindowHandles();
String currentHandle1 = driver.getWindowHandle();
for (String handle1 : handles1) {
if (!handle1 .equals(currentHandle1))
{
driver.switchTo().window(handle1);
}
}
Thread.sleep(3000L);
//To get new opened page URL and Title in new tab
String pUrl1 = driver.getCurrentUrl();
String pTitle1 = driver.getTitle();
HttpURLConnection c= (HttpURLConnection)new URL(pUrl1).openConnection();
c.connect();
int responseCode1 = c.getResponseCode();
if (responseCode1 != 200)
{
System.out.println(">> URL is "+pUrl1+" and title is "+pTitle1+ " is checked and Response code is "+responseCode1 + ". So page is failed.");
}
else {
System.out.println(">> URL is "+pUrl1+" and title is "+pTitle1+ " is checked and Response code is "+responseCode1 +". So page is passed");
}
driver.close();
driver.switchTo().window(currentHandle1);
}
}
else {
if (anchorlink.contains("#") )
{
System.out.println("Link not found");
continue;
}
else {
clickLink.get(i).sendKeys(clicklnk);
Thread.sleep(2000L);
}
//System.out.println("clicked");
Set<String> handles = driver.getWindowHandles();
String currentHandle = driver.getWindowHandle();
for (String handle : handles) {
if (!handle .equals(currentHandle))
{
driver.switchTo().window(handle);
}
}
Thread.sleep(3000L);
String pUrl = driver.getCurrentUrl();
String pTitle = driver.getTitle();
HttpURLConnection c= (HttpURLConnection)new URL(pUrl).openConnection();
c.connect();
int responseCode = c.getResponseCode();
if (responseCode != 200)
{
System.out.println(">> URL is "+pUrl+" and title is "+pTitle+ " is checked and Response code is "+responseCode + ". So page is failed.");
}
else {
System.out.println(">> URL is "+pUrl+" and title is "+pTitle+ " is checked and Response code is "+responseCode +". So page is passed");
}
driver.close();
driver.switchTo().window(currentHandle);
}
}
driver.quit();

How to use a loop to select items sequentially within Android app

Here I have 3 images with clickable elements :
I used this code so when it runs through the first loop, it selects the FIRST image :
driver.findElement(By.id("com.offerup:id/circle")).click();
After my code runs through the second loop, I want it to go back and select the SECOND image, and so on.
I've obtained my elements from uiautomatorviewer which can be seen here :
I am not sure on what command to use to fix my problem, could anyone help me out?
Here is my full code for better examination :
public void SimpleTest() throws InterruptedException {
driver.findElement(By.id("com.offerup:id/email_button")).click();
By path = By.xpath("//*[#text='Enter your email address']");
driver.findElement(path).sendKeys("xxxxx#gmail.com");
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/next_button")).click();
By path1 = By.xpath("//*[#text='']");
driver.findElement(path1).sendKeys("xxxxx");
driver.findElement(By.id("com.offerup:id/main_text")).click();
Thread.sleep(10000);
By path2 = By.xpath("//*[#text='OfferUp']");
driver.findElement(path2).click();
Thread.sleep(10000);
driver.findElement(By.id("com.offerup:id/nav_post_item")).click();
Thread.sleep(5000);
driver.findElement(By.id("com.offerup:id/addPhotoFromGallery")).click();
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
}
catch (Exception e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
}
By path3 = By.xpath("//*[#text='Name, brand, model, etc.']");
driver.findElement(path3).sendKeys("Iphone icloud unlocked");
driver.findElement(By.id("com.offerup:id/footer_button")).click();
driver.findElement(By.id("com.offerup:id/see_more")).click();
driver.findElement(By.id("com.offerup:id/category_list_row_text"));
By path4 = By.xpath("//*[#text='Cell Phones']");
driver.findElement(path4).click();
By path5 = By.xpath("//*[#text='Description']");
driver.findElement(path5).sendKeys("");
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/conditionSeekBar")).sendKeys(new CharSequence[] { " " });
driver.findElement(By.id("com.offerup:id/footer_button")).click();
By path6 = By.xpath("//*[#text='$0']");
driver.findElement(path6).sendKeys("200");
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/firmPrice")).click();
driver.findElement(By.id("com.offerup:id/footer_button")).click();
driver.findElement(By.id("com.offerup:id/edit")).click();
By path7 = By.xpath("//*[#text='Zip code']");
driver.findElement(path7).sendKeys("xxxx");
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/saveLocation")).click();
if(driver.findElement(By.id("com.offerup:id/shipping_checkbox")).isSelected()){
driver.findElement(By.id("com.offerup:id/shipping_checkbox")).click();
}
driver.findElement(By.id("com.offerup:id/footer_button")).click();
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/footer_button")).click();
Thread.sleep(4000);
driver.findElement(By.id("com.offerup:id/footer_button")).click();
driver.closeApp();
Thread.sleep(50000);
int index = 100;
do {
index --;
By path8 = By.xpath("//*[#text='OfferUp']");
driver.findElement(path8).click();
Thread.sleep(5000);
driver.findElement(By.id("com.offerup:id/nav_post_item")).click();
Thread.sleep(5000);
driver.findElement(By.id("com.offerup:id/addPhotoFromGallery")).click();
try {
driver.findElement(By.id("com.simplemobiletools.gallery:id/dir_thumbnail")).click();
driver.findElement(By.id("com.simplemobiletools.gallery:id/medium_thumbnail")).click();
}
catch (Exception e) {
driver.findElement(By.id("com.offerup:id/circle")).click();
driver.findElement(By.id("com.offerup:id/done")).click();
}
By path9 = By.xpath("//*[#text='Name, brand, model, etc.']");
driver.findElement(path9).sendKeys("Iphone XR Icloud unlocked"); // set ad name here
driver.findElement(By.id("com.offerup:id/footer_button")).click();
driver.findElement(By.id("com.offerup:id/see_more")).click();
driver.findElement(By.id("com.offerup:id/category_list_row_text"));
By path10 = By.xpath("//*[#text='Cell Phones']");
driver.findElement(path10).click();
By path11 = By.xpath("//*[#text='Description']");
driver.findElement(path11).sendKeys("");
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/conditionSeekBar")).sendKeys(new CharSequence[] { " " });
driver.findElement(By.id("com.offerup:id/footer_button")).click();
By path12 = By.xpath("//*[#text='$0']");
driver.findElement(path12).sendKeys("200");
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/firmPrice")).click();
driver.findElement(By.id("com.offerup:id/footer_button")).click();
driver.findElement(By.id("com.offerup:id/footer_button")).click();
Thread.sleep(2000);
driver.findElement(By.id("com.offerup:id/footer_button")).click();
Thread.sleep(4000);
driver.findElement(By.id("com.offerup:id/footer_button")).click();
driver.closeApp();
Thread.sleep(50000);
} while (index > 0);
index = index + 1;
}
}
Since you are trying to tap on the images in the grid layout. Here is the steps to achieve that.
Identify the grid element.
Add the row to a list.
Then traverse to each row to click on the image element.
Below is the code function which helps to achieve it.
public void selectPhotos(int numberOfPhotosToSelect){
//Find the grid element
WebElement gridAlbum= driver.findElement(By.xpath("xpath of the full grid of album"));
//Add the rows of element to the list
List<WebElement> gridRows=gridAlbum.findElements(driver.findElement(By.xpath("xpath of the row element");
//find the number of rows
System.out.println("Number of Rows"+gridRows.size());
for(WebElement row:gridRows) {
List<WebElement> cells=row.findElements(driver.findElement(By.xpath("xpath of the Image");
for(WebElement cell:cells) {
if(numberOfPhotosToSelect>0) {
cell.click();
numberOfPhotosToSelect--;
}
else
break;
}
}
}

java- How to set rollback function on inserting records to table?

I have a program where I extract some records from a PDF file, then I proceed to insert those records into a table in MySQL.
One of my main concern is if there is an error under any circumstances during the inserting to table. Let's say if I am inserting 1000 records from a file into the table and halfway, something bad happens. So does it auto rollback or do I need to include a "Begin Transaction and Commit Transaction" statement?
If so, how do I initiate a rollback inside Java? I am thinking of writing a rollback function just to achieve this.
My code:
public void index(String path) throws Exception {
PDDocument document = PDDocument.load(new File(path));
if (!document.isEncrypted()) {
PDFTextStripper tStripper = new PDFTextStripper();
String pdfFileInText = tStripper.getText(document);
String lines[] = pdfFileInText.split("\\r?\\n");
for (String line : lines) {
String[] words = line.split(" ");
String sql="insert IGNORE into test.indextable values (?,?)";
// con.connect().setAutoCommit(false);
preparedStatement = con.connect().prepareStatement(sql);
int i=0;
for (String word : words) {
// check if one or more special characters at end of string then remove OR
// check special characters in beginning of the string then remove
// insert every word directly to table db
word=word.replaceAll("([\\W]+$)|(^[\\W]+)", "");
preparedStatement.setString(1, path);
preparedStatement.setString(2, word);
preparedStatement.addBatch();
i++;
if (i % 1000 == 0) {
preparedStatement.executeBatch();
System.out.print("Add Thousand");
}
}
if (i > 0) {
preparedStatement.executeBatch();
System.out.print("Add Remaining");
}
}
}
// con.connect().commit();
preparedStatement.close();
System.out.println("Successfully commited changes to the database!");
}
This function above will be called by another function to be executed and the try and catch exception is in the caller function.
My rollback function:
// function to undo entries in inverted file on error indexing
public void rollbackEntries() throws Exception {
con.connect().rollback();
System.out.println("Successfully rolled back changes from the database!");
}
I appreciate any suggestions.
I don't know what library you are using, so I am just going to guess on exception names and types. If you look in the api you can check to see what exceptions are thrown by what functions.
private final static String INSERT_STATMENT = "insert IGNORE into test.indextable values (?,?)";
public void index(String path) { // Don't throw the exception, handle it.
PDDocument document = null;
try {
document = PDDocument.load(new File(path));
} catch (FileNotFoundException e) {
System.err.println("Unable to find document \"" + path "\"!");
return;
}
if (document == null || document.isEncrypted()) {
System.err.println("Unable to read data from document \"" + path "\"!");
return;
}
String[] lines = null;
try {
PDFTextStripper stripper = new PDFTextStripper();
lines = stripper.getText(document).split("\\r?\\n");
} catch (IOException e) {
System.err.println("Could not read data from document \"" + path "\"! File may be corrupted!");
return;
}
// You can add in extra checks just to test for other specific edge cases
if (lines == null || lines.length < 2) {
System.err.println("Only found 1 line in document \"" + path "\"! File may be corrupted!");
return;
}
for (String line : lines) {
PreparedStatement statement = con.connect().prepareStatement(INSERT_STATMENT );
String[] words = line.split(" ");
for (int index = 0, executeWait = 0; index < words.length; index++, executeWait++) {
preparedStatement.setString(1, path);
preparedStatement.setString(2, words[index].replaceAll("([\\W]+$)|(^[\\W]+)", ""));
preparedStatement.addBatch();
// Repeat this part again like before
if (executeWait % 1000 == 0) {
for (int timeout = 0; true; timeout++) {
try {
preparedStatement.executeBatch();
System.out.print("Pushed " + (((executeWait - 1) % 1000) + 1) + " statements to database.");
break;
} catch (ConnectionLostException e) {
if (timeout >= 5) {
System.err.println("Unable to resolve issues! Exiting...");
return;
}
System.err.println("Lost connection to database! Fix attempt " + (timeout + 1) + ". (Timeout at 5)");
con.reconnect();
} catch (SqlWriteException error) {
System.err.println("Error while writing to database. Rolling back changes and retrying. Fix attempt " + (timeout + 1) + ". (Timeout at 5)");
rollbackEntries();
if (timeout >= 5) {
System.err.println("Unable to resolve issues! Exiting...");
return;
}
}
}
}
}
}
try {
preparedStatement.close();
} catch (IOException e) {
// Do nothing since it means it was already closed.
// Probably throws an exception to prevent people from calling this method twice.
}
System.out.println("Successfully committed all changes to the database!");
}
There are definitely a few more exceptions which you will need to account for which I didn't add.
Edit: Your specific issue can be found at this link

I want to know how to save the string ID and use the same to compare anywhere in any member function?

In Selenium we have a situation where we need to get the ID "MANTPLAP300920141426403767374" from an application and store it in a Object type Variable. We picked the ID using gettext() method.
We need to relogin into the application with an different user and use the ID that was saved earlier in a Object type variable in another method. We require to match the ID by doing a compare in each of the page in the approver application(some other method).
If the match is found we need to check the box and approve the record of that ID.
Flow:
STep 1: Login as an user 1 create record and save its ID.
2: Since its a string we Copy the ID into an Object variable.
3: logoff the application
4: Login with an diffrent user to approve the record
5: Search for the ID that was created by the first user in differnt pages if not found in the first page.
Issue is: We have one Java class where we are successfully storing the ID. After relogin into the application as a different user we are unaware how to call that object type variable and use it in that particular class.
In the debug mode we get NULL as the reference ID instead of saved ID "MANTPLAP300920141426403767374"
We want to know how to save the string ID and use the same to compare anywhere in any member function ?
CommonFunction Library.java
public static void getSourceRefId(String object,String data ) throws InterruptedException {
try{
{
ArrayList<String> NewTab = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(NewTab.get(1));
String SourceRefId=driver.findElement(By.id(OR.getProperty(object))).getText();
System.out.println("the value is "+ SourceRefId);
Log.info(" Required source ref is present in the applicaiton"+ object);
}
} catch (NoSuchElementException e){
Log.error("Not able to get the source ref id--- " + e.getMessage());
driver.close();
}
}
public static void searchSourceRefId(String object,String data ) throws InterruptedException{
try{
WindowsUtils.tryToKillByName("chromedriver.exe");
Thread.sleep(10000);
Log.info("Searching source ref id started");
WebDriver driver = null;
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://tpl.test.open.url.com/portal/login.do");
driver.findElement(By.name("j_username")).sendKeys("appoascgval1");
driver.findElement(By.name("j_password")).sendKeys("Password1");
driver.findElement(By.xpath("//input[#type='submit']")).click();
Thread.sleep(10000);
driver.findElement(By.xpath("//a[contains(text(),'Validation')]")).click();
Thread.sleep(30000);
//Getting the pages
List<WebElement> allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
System.out.println(allpages.size());
if(allpages.size()>0)
{
System.out.println("Pagination exists");
for(int i=0; i<=allpages.size(); i++)
{
//allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
List<WebElement> allrows = driver.findElements(By.xpath("//*[#id='content']/div[3]/table/tbody/tr"));
System.out.println("Total rows :" +allrows.size());
for(int row=1; row<=allrows.size(); row++)
{
System.out.println("Total rows :" +allrows.size());
allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
String validatorSoruceRefId = driver.findElement(By.xpath("//*[#id='content']/div[3]/table/tbody/tr["+row+"]/td[7]")).getText();
System.out.println(validatorSoruceRefId);
System.out.println("Row loop");
if(validatorSoruceRefId==Constants.SourceRefId){
// if(validatorSoruceRefId.contains("MANTPLAP300920141426403767374")){
System.out.println("is it found");
Log.info("Source id found" );
break;
}
else
{
System.out.println("Element doesn't exist");
// allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
}
}
System.out.println("I'm in page number" + i);
Thread.sleep(3000);
allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
allpages.get(i).click();
driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
//System.out.println(i);
}
}
else
{
System.out.println("Pagination doesn't exists");
}
}catch (IndexOutOfBoundsException e) {
}
}
}
Please help me to resolve this.
Store the first ID as a static variable and access it again (after logging in as a second user).
Try this code please:
static String SourceRefId;
public static String getSourceRefId(String object,String data ) throws InterruptedException {
try{
ArrayList<String> NewTab = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(NewTab.get(1));
SourceRefId=driver.findElement(By.id(OR.getProperty(object))).getText();
System.out.println("the value is "+ SourceRefId);
Log.info(" Required source ref is present in the applicaiton"+ object);
} catch (NoSuchElementException e){
Log.error("Not able to get the source ref id--- " + e.getMessage());
return SourceRefId;
}
}
public static void searchSourceRefId(String object,String data ) throws InterruptedException{
try{
WindowsUtils.tryToKillByName("chromedriver.exe");
Thread.sleep(10000);
//Log.info("Searching source ref id started");
WebDriver driver = null;
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://tpl.test.open.url.com/portal/login.do");
driver.findElement(By.name("j_username")).sendKeys("appoascgval1");
driver.findElement(By.name("j_password")).sendKeys("Password1");
driver.findElement(By.xpath("//input[#type='submit']")).click();
Thread.sleep(10000);
driver.findElement(By.xpath("//a[contains(text(),'Validation')]")).click();
Thread.sleep(30000);
//Getting the pages
List<WebElement> allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
System.out.println(allpages.size());
if(allpages.size()>0)
{
System.out.println("Pagination exists");
for(int i=0; i<=allpages.size(); i++)
{
//allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
List<WebElement> allrows = driver.findElements(By.xpath("//*[#id='content']/div[3]/table/tbody/tr"));
System.out.println("Total rows :" +allrows.size());
for(int row=1; row<=allrows.size(); row++)
{
System.out.println("Total rows :" +allrows.size());
allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
String validatorSoruceRefId = driver.findElement(By.xpath("//*[#id='content']/div[3]/table/tbody/tr["+row+"]/td[7]")).getText();
System.out.println(validatorSoruceRefId);
System.out.println("Row loop");
if(validatorSoruceRefId.equals(SourceRefId)){
// if(validatorSoruceRefId.contains("MANTPLAP300920141426403767374")){
System.out.println("is it found");
Log.info("Source id found" );
break;
}
else
{
System.out.println("Element doesn't exist");
// allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
}
}
System.out.println("I'm in page number" + i);
Thread.sleep(3000);
allpages = driver.findElements(By.xpath("//div[#class='content-table-pagination']//a"));
allpages.get(i).click();
driver.manage().timeouts().pageLoadTimeout(50, TimeUnit.SECONDS);
//System.out.println(i);
}
}
else
{
System.out.println("Pagination doesn't exists");
}
}catch (IndexOutOfBoundsException e) {
}
}
In the above code I have made the following changes:
Made SourceRefId as static
Changed the return type of method "getSourceRefId" to String so that it will return the "SourceRefId".
Lost the extra brackets inside try block of method "getSourceRefId".
Removed driver.close() from the method "getSourceRefId" and replaced it with the "return SourceRefId" that returns the value to be compared
And, finally changed the "if(validatorSoruceRefId==Constants.SourceRefId)" to "if(validatorSoruceRefId.equals(SourceRefId))" as Strings are compared here.
Hope this works out for you.

Selenium WebDriver By.xpath doesn't work all the time

Info :
I get fieldXpath from a config file, and it is "//input[#id='signin_password']"
HTML :
<li><input type="password" name="signin[password]" id="signin_password" /></li>
WORKS : (but not always)
Gets in the catch ...
public void doAction(WebDriver driver) throws TestException {
try {
WebElement el = driver.findElement(By.xpath(fieldXpath));
el.clear();
el.sendKeys(fieldValue);
} catch (Exception e) {
throw new TestException(this.getClass().getSimpleName() + ": problem while doing action : " + toString());
}
}
Does a solution that makes this code work with XPath?
I found the problem... : selenium WebDriver StaleElementReferenceException
*This may be caused because the page isn't loaded completely when the code starts or changes when the code is executed. You can either try to wait a little longer for the element or catch the StaleReferenceException and try again finding the div and the span.*
My code : (call these functions before each field)
/**
* Handle StaleElementReferenceException
* #param elementXpath
* #param timeToWaitInSec
*/
public void staleElementHandleByXpath(String elementXpath, int timeToWaitInSec) {
int count = 0;
while (count < 10) {
try {
WebElement slipperyElement = driver.findElement(By.xpath(elementXpath));
if (slipperyElement.isDisplayed()) {
slipperyElement.click(); // may throw StaleElementReferenceException
}
count = count + 10;
} catch (StaleElementReferenceException e) {
count = count + 1; // try again
} catch (ElementNotVisibleException e) {
count = count + 10; // get out
} catch (Exception e) {
count = count + 10; // get out
} finally {
// wait X sec before doing the action
driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS);
}
}
}
/**
* Wait till the document is really ready
* #param js
* #param timeToWaitInSec
*/
public void waiTillDocumentReadyStateComplete(JavascriptExecutor js, int timeToWaitInSec) {
Boolean ready = false;
int count = 0;
while (!ready && count < 10) {
ready = (Boolean) js.executeScript("return document.readyState == 'complete';");
// wait X sec before doing the action
driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS);
count = count + 1;
}
}
Use single ' quotes instead of ". So
String fieldXpath = "//input[#id='signin_password']";

Categories