enter image description herejava
List<WebElement> group = driver.findElements(By.xpath("//*[#ng-repeat='employeeGroup in employeeGroups']"));
for (int k = 0; k < group.size(); k++) {
if (group.get(k).getText().toLowerCase().startsWith(shuttleObj.getGroupName().toLowerCase())) {
group.get(k)
.findElement(
By.xpath("//body//div[" + (k + 2) + "]//li[1]/ul/a/i"))
.click();
Thread.sleep(500);
String firstparent = driver.getWindowHandle();
for (String firstchild : driver.getWindowHandles()) {
driver.switchTo().window(firstchild);
Thread.sleep(1000);
driver.findElement(By.xpath(props.getProperty("thirdEmployee"))).click();
Thread.sleep(200);
driver.findElement(By.xpath(props.getProperty("fourthEmployee"))).click();
Thread.sleep(200);
driver.findElement(By.xpath(props.getProperty("selectedEmployeeTab"))).click();
Thread.sleep(200);
}
driver.switchTo().window(firstparent);
Thread.sleep(2000);
group.get(k).findElement(By.xpath("//body//div[" + (k + 2) + "]//li[2]/ul/a/i")).click();
String secondparent = driver.getWindowHandle();
for (String secondchild : driver.getWindowHandles()) {
driver.switchTo().window(secondchild);
Thread.sleep(1000);
driver.findElement(By.xpath(props.getProperty("thirdEmployee"))).click();
Thread.sleep(200);
driver.findElement(By.xpath(props.getProperty("fourthEmployee"))).click();
Thread.sleep(200);
driver.findElement(By.xpath(props.getProperty("selectedEmployeeTab"))).click();
Thread.sleep(200);
driver.switchTo().window(secondparent);
}
}
I amup able to click first child but I can't be able to click second child.
This is giving the error is: Message:
stale element reference: element is not attached to the page document
you have to switch to base page before switching to the second page in the loop, as shown in the below code.
for (String secondchild : driver.getWindowHandles()) {
driver.switchTo().window(secondchild);
Thread.sleep(1000);
driver.findElement(By.xpath(props.getProperty("thirdEmployee"))).click();
Thread.sleep(200);
driver.findElement(By.xpath(props.getProperty("fourthEmployee"))).click();
Thread.sleep(200);
driver.findElement(By.xpath(props.getProperty("selectedEmployeeTab"))).click();
Thread.sleep(200);
driver.switchTo().defaultContent();
driver.switchTo().window(secondparent);
}
Related
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
What could be wrong the with below selenium code?
In console i'm unable to see any error or exception. After executing below code i can print 0,1,2 but not able to print 3 and 4.
#Test(priority = 9, retryAnalyzer = com.brcc.tool.RetryFailedTestCases.RetryTestCases.class)
public void findSearchable() throws InterruptedException {
wait = new WebDriverWait(driver, 40);
System.out.println("0");
List<WebElement> searchableElements = driver
.findElements(By.cssSelector(prop.getProperty("searchableElements")));
System.out.println("1");
List<String> searchable = new ArrayList<String>();
System.out.println("2");
for (WebElement searchableElement : searchableElements) {
System.out.println("3");
searchable.add(searchableElement.getText());
System.out.println("searchable = " + searchable);
System.out.println("Size of list = " + searchable.size());
}
System.out.println("searchableList = " + searchable);
for (int i = 0; i < searchable.size() - 1; i++) {
System.out.println("4");
if ((searchable.get(i).contains(sftpCon.searchableFields("Searchable Fields", 0))) && (searchable.get(i).contains(sftpCon.searchableFields("Searchable Fields", 1)))
&& (searchable.get(i).contains(sftpCon.searchableFields("Searchable Fields", 2))) && (searchable.get(i).contains(sftpCon.searchableFields("Searchable Fields", 3)))) {
System.out.println("Got it ...... = " + searchable.get(i));
} else {
System.out.println("Not Found");
}
}
}
If you see the values when running the script in debug mode not in the normal execution mode, then please make sure the elements are loaded before getting searchableElements.
Change the below line
List<WebElement> searchableElements = driver
.findElements(By.cssSelector(prop.getProperty("searchableElements")));
to use the webdriverwait
List<WebElement> searchableElements = new WebDriverWait(driver, maxTimeOut))
.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(prop.getProperty("searchableElements")))
//print the size here
System.out.println("Number of list items:-" + searchableElements.size());
Now my issue has been fixed, after using below code
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List searchableElements = driver.findElements(By.cssSelector(prop.getProperty("searchableElements")));
I'm not able to make it Wright in an username at https://mail.protonmail.com/create/new?language=en. For some reason it cant find or cant klick at "choose username", Can any one help me out?
Code trials:
public class LaunchApplication {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
int number = 1;
String url = "https://protonmail.com";
String password = "passwordpassword123123";
String username = "";
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rand = new Random();
int length = 8;
while (number > 0){
//Create an random string for the user name:
// video of how to make string randomicer https://www.youtube.com/watch?v=CZYeTblcOU8 check it out
char[] text = new char[length];
for(int i = 0; i < length; i++){
text[i] = characters.charAt(rand.nextInt(characters.length()));
}
for(int i = 0; i < text.length; i++){
username += text[i];
}
System.out.println(username);
Thread.sleep(2000);
//Program starting: video to make it all work https://www.youtube.com/watch?v=QY0iQpX0LDU
driver.get(url);
System.out.println(driver.getTitle());
Thread.sleep(2000);
driver.findElement(By.linkText("SIGN UP")).click();
Thread.sleep(5000);
driver.findElement(By.className("panel-heading")).click();
Thread.sleep(2000);
driver.findElement(By.id("freePlan")).click();
Thread.sleep(5000);
System.out.println("Here");
Thread.sleep(5000);
System.out.println("pass1");
driver.findElement(By.name("password")).sendKeys(password);
System.out.println("pass2");
driver.findElement(By.name("passwordc")).sendKeys(password);
Thread.sleep(2000);
System.out.println("Username here");
try{
driver.findElement(By.id("username")).click();
}catch (Exception E){
System.out.println("DOnt work1");
}
try{
driver.findElement(By.name("username")).click();
}catch (Exception B){
System.out.println("DOnt work2");
}
try{
driver.findElement(By.id("input")).click();
}catch (Exception A){
System.out.println("DOnt work3");
}
try{
driver.findElement(By.linkText("Choose")).click();
}catch (Exception A){
System.out.println("DOnt work4");
}
try{
driver.findElement(By.xpath("//input[#id='#username.input']")).click();
}catch (Exception A){
System.out.println("DOnt work5");
}
try{
driver.findElement(By.tagName("messages=\"[object Object]\"")).click();
}catch (Exception A){
System.out.println("DOnt work6");
}
number = number-1;
}
}
}
To click() within the element with placeholder as Choose username within the url https://mail.protonmail.com/create/new?language=en, as the the desired element is within a <iframe> so you have to:
Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt.
Induce WebDriverWait for the desired elementToBeClickable.
You can use either of the following Locator Strategies:
Using cssSelector:
driver.get("https://mail.protonmail.com/create/new?language=en");
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("div.usernameWrap iframe[title='Registration form']")));
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.input#username"))).click();
Using xpath:
driver.get("https://mail.protonmail.com/create/new?language=en");
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//div[#class='usernameWrap']//iframe[#title='Registration form']")));
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='input' and #id='username']"))).click();
Browser Snapshot:
Reference
You can find a couple of relevant discussions in:
Ways to deal with #document under iframe
Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?
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;
}
}
}
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.