Why can't selenium webdriver see the elements on the webpage? (NoSuchElementException) - java

I have my selenium code here
System.out.println("Selects selected");
Methods methods = new Methods();
/**
there's some code here, but it's just a lot of driver().findElement() and updating values in fields. It works OK
**/
driver().findElement(By.xpath("//*[#id=\"updateclient\"]")).click();
Thread.sleep(5000);
driver().findElement(By.xpath("//*[#id=\"quoteclient\"]")).click();
Thread.sleep(15000);
/* Selects the Zurich Quote (Only one currently working) */
driver().findElement(By.xpath("//*[contains(#id, 'quote-0')]//*[contains(#alt, 'Zurich')]")).click();
/* Select the Apply for Big 3 CIC button */
driver().findElement(By.xpath("//*[#id=\"apply_for_big3\"]")).click();
//Just wait for the page to load properly
Thread.sleep(2500);
/**
* Now we are at the big3 eligibility page. We will need to enter the client details.
* Because we want to check all the outcomes that iptiQ have given us, we're going to do
* this in a loop.
*
* This loop will set the client details, answer the questions, and then go through to the
* quoting page.
*
* When the client has been quoted for the values set, we will check that the premium matches
* the expected value.
*
* At the end of each iteration, the user will be returned to the Big3 eligibility screen so that
* the next set of values can be set.
*/
//Get the fields. -------
//This is the bit that keeps failing and it should not be failing
// because the elements are all present on the page
WebElement EligibilityTitleOne = driver().findElement(By.xpath("//*[#id=\"title_1\"]"));
WebElement EligibilityForenameOne = driver().findElement(By.xpath("//*[#id=\"forename_1\"]"));
WebElement EligibilitySurnameOne = driver().findElement(By.xpath("//*[#id=\"surname_1\"]"));
String[][] SumAssuredCases = QuoteGraph.SingleLifeSumAssured;
for(int i=0; i<SumAssuredCases.length; i++){
/**
//Extract all the required values from the array
int AgeNextBirthDay = Integer.parseInt(SumAssuredCases[i][1]);
String SmokerStatus = SumAssuredCases[i][2];
String SumAssured = SumAssuredCases[i][5].replace(",","");
String PolicyTerm = SumAssuredCases[i][6];
String ExpectedPremium = SumAssuredCases[i][7];
String ExpectedCommission = SumAssuredCases[i][8];
**/
int AgeNextBirthDay = 25;
String SmokerStatus = "NonSmoker";
String SumAssured = "10000";
//We are going to use a pre set name, as names do not affect the premium.
EligibilityTitleOne.clear();
EligibilityTitleOne.sendKeys("Mr");
System.out.println("Set customer 1 title");
EligibilityForenameOne.clear();
EligibilityForenameOne.sendKeys("Tester");
System.out.println("Set customer 1 forename");
EligibilitySurnameOne.clear();
EligibilitySurnameOne.sendKeys("Testeez");
System.out.println("Set customer 1 surname");
//Now we are going to set the sex to be male. This does not affect the premium.
Select clientOneSexSelect = new Select(driver().findElement(By.xpath("//*[#id=\"gender_1\"]")));
clientOneSexSelect.selectByVisibleText("Male");
System.out.println("Set customer 1 to male");
//Now we need to set the smoker status from the value in the customer profile
Select clientOneSmokerStat = new Select(driver().findElement(By.xpath("//*[#id=\"smoker_1\"]")));
if(SmokerStatus.matches("Smoker")) {
clientOneSmokerStat.selectByVisibleText("Yes");
System.out.println("Customer 1 is a smoker.");
} else {
clientOneSmokerStat.selectByVisibleText("No");
System.out.println("Customer 1 is not a smoker.");
}
//Now we need to calculate the date of birth
String customerOneDob = methods.DOBFromAge(AgeNextBirthDay);
driver().findElement(By.xpath("//*[#id=\"dob_1\"]")).sendKeys(customerOneDob);
System.out.println("Customer 1 date of birth set to " + customerOneDob);
//Now we need to set the sum assured value
driver().findElement(By.xpath("//*[#id=\"sum_assured\"]")).clear();
driver().findElement(By.xpath("//*[#id=\"sum_assured\"]")).sendKeys(SumAssured);
System.out.println("Sum assured set to £" + SumAssured);
//Select the update client details
driver().findElement(By.xpath("//*[#id=\"update_lead\"]")).click();
//Wait for update to complete
Thread.sleep(1000);
System.out.println("The changes have been saved.");
Thread.sleep(2500);
}
and all the driver().findElement(By.xpath()) have worked fine up until the point when I need to fill out the form repeatedly in the loop, and suddenly I start getting the NoSuchElementException error.
I don't understand why I am getting the error, when the webpage I am on has all the fields, I have taken the xpaths directly from [right click]->[copy xpath] in devtools.
The fields are definitely there and the XPATH I am using is correct, I've checked multiple times and so have my colleages, but I don't know why it gets to just before the loop and then stops working.
I've also tried findElement(By.id()) but that still gave me the same error. Selenium is acting as though the elements don't exist, even though they do.

Check if the elements are with in IFrame then use driver.switchto.frame (frmaelocator);
If it's on a different tab use windowhandles

Related

Select value from drop down autocomplete

I use cssselector with Keys class. But the value is not selected
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes", Keys.DOWN, Keys.ENTER);
I want to select the value Odessa from drop down list:
I'm not sure how the website is populating that dropdown, but maybe you could enter your text and then select the first option like this:
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes");
browser.findElement(By.cssSelector("input[id='loadingPort']")).findElements(By.tagName("option")).get(0).click()
/** OR */
browser.findElement(By.cssSelector("input[id='loadingPort']:first-child")).click()
Sorry, I'm not familiar with java or cssSelectors... just Selenium. If you can clean up that code, that should work if the website is dynamically adding options to the dom.
One more using xpath:
browser.findElement(By.xpath("input[#id='loadingPort']/option[1]")).click()
There are multiple ways to handle dropdown value
- dropdown.selectByVisibleText("Text");
- dropdown.selectByIndex(2); (Index starts with zero always in list)
- dropdown.selectByValue(“Text”)
Sample Code:
Select oSelect = new Select(driver.findElement(By.cssSelector("input[id='loadingPort']")));
// Select option (Odessa(UKR))
oSelect.selectByVisibleText("Odessa(UKR)"); // Using sleep command so that changes can be noticed
Thread.sleep(2000);
// : Select option 'using Index
oSelect.selectByIndex(1);
Thread.sleep(2000);
// Print all the options for the selected drop down and select one option of your choice
// Get the size of the Select element
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();
// Setting up the loop to print all the options
for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();
// Printing the stored value
System.out.println(sValue);
// Putting a check on each option that if any of the option is equal to 'Africa" then select it
if(sValue.equals("Odessa(UKR)")){
oSelect.selectByIndex(i);
break;
}
}

How to break the loop if webelement value matches to excel value

I am using application which has 19 pages. on each page there are 10 accounts and 10 checkboxes in front of them.
I have kept a list of some accounts in excel sheet and want to read account number in excel one by one, match it with accounts on webpage, if value matched->set the checkbox in front of that account and move for the next account in excel.....and this way repeat till last account is matched in excel list.
If account is not matched with any of the 10 accounts on webpage, i need to click on next arrow(present below account list on webpage) and check if account number matches with any of the account on new webpage.
code is as below
String data=null; //to get value of account on webpage
int count=0;
do{
for(count=0;count<=9;count++)
{
data= (String) al1.get(count); //al1=List of accounts on webelement
if(stg.equals(data)) //stg=account read from execl
{
utl.checkbox_clicking(data);//calling method to set checkbox if value matches
break;
}
}
utl.Weblement_Click("*name of weblement of next page arrow*");
al1 = utl.Account_List(); //loading new account list on next page in List
}while(stg.equals(data));
There is some problem in logic. Can somebody suggest the what changes i should make?
I see that your problem is when you find what you need you just execute break. But break go just out the inner loop, and not the outer.
So without trying to change anything in your code and reorganize something I want to tell that there is something unused in java, maybe because of unreadability of the code, that called labeled block. Maybe one of the only uses of it is to break out of outer loops. I hope it will help you and it's the right solution for your problem.
Note that most of the time if you find yourself using it maybe you need to change your loop. In your case I would go with something like while loop with two conditions: one for 10 account in each page and one when you can't find more pages.
here's a short tutorial about that:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
So in your code I just added the the first statement and the break line.
pagesLoop:
do {
for (count = 0; count <= 9; count++) {
data = (String) al1.get(count); //al1=List of accounts on webelement
if (stg.equals(data)) //stg=account read from execl
{
utl.checkbox_clicking(data);//calling method to set checkbox if value matches
break pagesLoop;
}
}
utl.Weblement_Click("*name of weblement of next page arrow*");
al1 = utl.Account_List(); //loading new account list on next page in List
} while (stg.equals(data));
Removing unnecessary loop and also missed count should be count<9 instead of count<=9
for(int count=0;count<9;count++) {
String data = (String) al1.get(count); //al1=List of accounts on webelement
if(stg.equals(data)) //stg=account read from execl
{
utl.checkbox_clicking(data);//calling method to set checkbox if value matches
break;
}
}
utl.Weblement_Click("*name of weblement of next page arrow*");
al1 = utl.Account_List(); //loading new account list on next page in List

How to retain newly added values on a two-dimensional array (JAVA)

I'm stuck at this part of my program. These are 2 options for my Student Information System (not using GUI/JOption and without linking to a database. I already have a 2-dimensional array (String records[][] = new String [5][3];) that has the first 2 "rows" ([0][0] to [0][2] and [1][0] to [1][2]) filled up with pre-assigned data (First Name, Last Name, Course).
If you look below, the part where "b" or "B" option is selected, this is for adding new values to a new array (incremented so that when option B is used, it will assign first [2][0], then [3][0]
and so on). It seemed to work since it does show that all the data I've entered was added and is displayed in the proper order. THE PROBLEM IS: when I choose 'Y" to return to the top menu and select option A to VIEW the newly added record (using ID number 2), it shows that it contains all "null". Is there something I've missed? This is the missing step I need in order to finish this program. Thanks ahead for the help.
if("a".equals(option1)|| "A".equals(option1)){
System.out.println("Please enter the Student ID for the record to view.");
String a = reader1.readLine();
idcheck = Integer.parseInt(a);
x1=idcheck;
for(int y=0;y<3;y++){
System.out.print(records[x1][y] + " ");
}
System.out.println("\nReturn to Main Menu or Exit? (Y/N)");
cont1= reader1.readLine();
}
else if("b".equals(option1)||"B".equals(option1)){
arr_count++;
for (int y = 0; y<3;y++){
System.out.println("Enter Value for "+ option [y]+":" );
String X = reader1.readLine();
records[arr_count][y] = X;
}

How to get fixed number of tweets using twitter4j

I am using Twitter4j to build a client to fetch tweets for the input search term. I am also trying to provide the facility to the user to enter the number of tweets he wants in the result.
I know that we can set the number of tweets to be returned per page with the Query's setCount() method:
Query q = new Query(searchTerm);
q.setCount(maxTweets);
But if I am giving the value 1 as maxTweets, it returns 2 tweets.
Update: After further research I observed that it is returning 1 extra tweet per search. So I am giving 1 as maxTweets value it is returning 2 tweets. If I am giving 2 as maxTweets value it is returning 3 tweets and so on.
I am not sure where I am wrong but please let me know if there is a way by which I can get the fixed number of tweets using twitter4j.
Any guidance will be helpful.
When you write
Query q = new Query(searchTerm);
Think of it as one tabled page which contains an amount of result matching your query. But there might be more multiple pages.
When you set
q.setCount(maxTweets);
it will bring you maxTweets amount of tweets per page. In your case, 2, because there were two pages matching your query and you selected one tweet per page.
What you can do, try to handle it with a do - while loop.
Query q = new Query(searchTerm);
QueryResult result;
int tempUSerInput = 0; //keep a temp value
boolean flag = false;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
tempUSerInput = tempUSerInput + tweets.size();
if(tempUSerInput >= realyourUserInput) // you have already matched the number
flag = true; //set the flag
}
while ((query = result.nextQuery()) != null && !flag);
// Here Take only realyourUserInput number
// as you might have taken more than required
List<Status> finaltweets = new ArrayList();
for(int i=0; i<realyourUserInput; i++)
finaltweets.add( tweets.get(i) ); //add them to your final list

Validating the sorting functionality using Selenium (Java)

This is my first post for help. Please correct me if you see anything wrong with my post.
I am trying to validate the sorting functionality in a web page with Selenium script (using java). here are the details...
First I go to a User search results page with multiple pages.
It has users with the details: user name, number of miles.
There is a sort filter drop down with values: Values A-Z, Values Z-A, Miles Most, Miles Least, Newest Members, Oldest members . by default the sorting is newest members.
Initially I just want to validate: Values A-Z, Values Z-A, Miles Most and Miles Least Since I could see those values in the search page.
For someone who is looking to solve the same problem. Below code worked for me in validating the sorting of all the string values in a page
//Declare Variables
int eleCount;
List<String> customerNameA = new ArrayList();
List<String> customerNameB = new ArrayList();
// Check for our Customer elements and count them.... replace xxx with your xpath
assertTrue(isElementPresent(By.xpath("xxx")));
elements = driver.findElements(By.xpath("xxx']"));
eleCount = elements.size();
System.out.println("Element count: " + eleCount);
for(int i = 2; i < eleCount; i++){
//Capture the customer name values
//replace xxx with your xpath & replace the value increments for each element in xpath with + i +
customerNameA.add(driver.findElement(By.xpath("xxx")).getText());
System.out.println(driver.findElement(By.xpath("xxx")).getText());
customerNameB.add(driver.findElement(By.xpath("xxx")).getText());
}
Collections.sort(customerNameA);
for (int i=0;i<customerNameA.size();i++) {
System.out.println("Customer Name from input: " + customerNameB.get(i) + "--Customer Name from sorted input: " + customerNameA.get(i));
if (!(customerNameA.get(i).equals(customerNameB.get(i)))) {
System.out.println("Customer Names not sorted: " + i);
break;
}
}
}

Categories

Resources