Below code is not handelling new window in selenium webdriver - selenium-webdriver

To handle multiple windows I have written below code. Its not giving me any error, however no action is getting performed on new window. Can you please help me to fix this issue or suggest me any other way. Thanks!
Code:
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
FirefoxDriver dw2 = new FirefoxDriver();
dw2.get("http://quercus0638v.quercus.kpn.org:90");
//OPEN login and provide credentials
dw2.manage().window().maximize();
Thread.sleep(2000);
dw2.findElement(By.id("ContentPlaceHolder1_GebruikersnaamTextBox")).clear();
dw2.findElement(By.id("ContentPlaceHolder1_GebruikersnaamTextBox")).sendKeys("behdse");
dw2.findElement(By.id("ContentPlaceHolder1_WachtwoordTextBox")).clear();
dw2.findElement(By.id("ContentPlaceHolder1_WachtwoordTextBox")).sendKeys("fiet$hok");
//Login : Clcik on Login button
dw2.findElement(By.id("ContentPlaceHolder1_LoginButton")).click();
//Click on Select button. After that new window will open
dw2.findElement(By.id("ContentPlaceHolder1_CWDatumRadioButton")).click();
// Below code I written to get the window handles
Set<String> AllWindowHandles = dw2.getWindowHandles();
String window1 = (String) AllWindowHandles.toArray()[0];
System.out.print("window1 handle code = "+AllWindowHandles.toArray()[0]);
String window2 = (String) AllWindowHandles.toArray()[1];
System.out.print("\nwindow2 handle code = "+AllWindowHandles.toArray()[1]);
//Switch to window2(child window) and performing actions on it.
dw2.switchTo().window(window2);
//Click the user
dw2.findElement(By.id("AfdelingGebruikersListView_RowCheckBox_8")).click();
//Click on OK button after selecting User
dw2.findElement(By.id("AfdelingGebruikersListView_OKButton")).click();
//Switch to window1(child window) and performing actions on it.
dw2.switchTo().window(window1);
//Click the order type you want to retrieve
dw2.findElement(By.id("ContentPlaceHolder1_VerwerktRadioButton")).click();
//Click for exporting the data to Excel Sheet
dw2.findElement(By.id("ContentPlaceHolder1_ExporteerNaarExcelButton")).click();
}

U can switch to windows using:
for (String winHandle : objDriver.getWindowHandles()) {
objDriver.switchTo().window(winHandle);
}
This will switch to the last window opened. To get back to parent window by again using the above code. It would be better that u incorporate the code in a different method in order to reuse.
Hope this helps. Thanks.

Editing the Code as per the comment by OP :-
Since, as I suggested in comment, it might not be a new window. It must be a pop-up. So, please replace your code as below and try:
//Click on Select button. After that new window will open
dw2.findElement(By.id("ContentPlaceHolder1_CWDatumRadioButton")).click()
//Click the user
try{
WebDriverWait wait = new WebDriverWait(dw2,20);
WebElement ele = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("AfdelingGebruikersListView_RowCheckBox_8")));
ele.click();
}catch(Throwable e){
System.err.println("Error while clicking on the element. "+e.getMessage());
}
//Click on OK button after selecting User
dw2.findElement(By.id("AfdelingGebruikersListView_OKButton")).click();

Related

In Selenium how to handle a new window?

I am writing a selenium script to login and create new mail, send it and logout. But when I click on New mail button, it opens a new window. In selenium how I can handle this. I am new to selenium. Please explain in detail.
Use the below code, you have to use getWindowHandles- I hope it helps, Let me know in case you get stuck anywhere else -
#Test
public void multipleWindows() {
driver.get(URL+"/windows");
driver.findElement(By.cssSelector(".example a")).click();
Object[] allWindows = driver.getWindowHandles().toArray();
driver.switchTo().window(allWindows[0].toString());
Assert.assertNotEquals(driver.getTitle(), "New Window");
driver.switchTo().window(allWindows[1].toString());
Assert.assertEquals(driver.getTitle(), "New Window");
}
}
How to get Window Handle:
String handle = driver.getWindowHandle();
If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -
Set windowHandles = driver.getWindowHandles();
"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.
How to switch to correct / appropriate window:
Basically there are two ways to switch to appropriate window.
By using windowName
driver.switchTo().window( "windowName" );
OR
To get current/parent/default window handle:
String handle = driver.getWindowHandle();
driver.switchTo().window( handle );
OR
Set < String > windowHandles = driver.getWindowHandles();
for(String handle : windowHandles )
{
driver.swicthTo().window( handle );
}
Example of Handling Multiple Windows In Selenium
Try this code, it is very easy to understand.
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/popup.php");
driver.findElement(By.xpath("html/body/p/a")).click();
// return the parent window name as a String
String parentWindow=driver.getWindowHandle();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Pass a window handle to the other window
for(String childWindow: driver.getWindowHandles())
{
System.out.println("Switch to child window");
//switch to child window
driver.switchTo().window(childWindow);
//find an element and print text of it
WebElement textLabel=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println(" text: "+textLabel.getText());
driver.close();
}
System.out.println("Get back to parent window");
//switch to Parent window
driver.switchTo().window(parentWindow);
//find an element and print text of it
WebElement logotext=driver.findElement(By.xpath("html/body/div[1]/h2"));
System.out.println("text: "+logotext.getText());
driver.close();
}

Code is not getting executable after opening pop up in selenium

Please find below the code :
d.findElement(By.id("txtUserName")).clear();
d.findElement(By.id("txtUserName")).sendKeys("polarissupport#polaristest.net");
Thread.sleep(2000);
d.findElement(By.name("txtTempBox")).clear();
Thread.sleep(2000);
d.findElement(By.id("txtPassword")).sendKeys("password");
d.findElement(By.id("btnsubmit")).click();
Thread.sleep(2000);
d.findElement(By.id("ctl00_ContentPlaceHolder1_rdoAdmin")).click();
Thread.sleep(2000);
d.findElement(By.id("ctl00_ContentPlaceHolder1_lnkContinue")).click();
Thread.sleep(5000);
//GC Inbox
String s1 = "CHR-665";//d.findElement(By.id("ctl00_ContentPlaceHolder1_lblrequestidtext")).getText(); //For taking Request Id
String tem[] = s1.split("-");
d.findElement(By.id("ctl00_ContentPlaceHolder1_ctlCommonInbox_txtGrantID")).sendKeys(tem[1]);
d.findElement(By.id("ctl00_ContentPlaceHolder1_ctlCommonInbox_lnkSearch")).click();
Thread.sleep(5000);
d.findElement(By.id("ctl00_ContentPlaceHolder1_ctlCommonInbox_grdAdminGrantCHR_ctl00_ctl04_btnAction")).click();
Thread.sleep(8000);
d.findElement(By.xpath("//*[#id='ctl00_ContentPlaceHolder1_lnkReleasePayment']")).click();
After the last line which opens the Pop-up, code is not getting executable to handle this opened Pop-up.
Please find below the code through which I handled the Pop-up:
String MainWindow=d.getWindowHandle();
Set<String> set=d.getWindowHandles();
Iterator<String> it=set.iterator();
while(it.hasNext())
{
System.out.println("Inside While");
String ChildWindow=it.next();
if(!MainWindow.equalsIgnoreCase(ChildWindow))
{
d.switchTo().window(ChildWindow);
d.close();
}
}
System.out.println("Outside While");
d.switchTo().window(MainWindow);
Please let me know how to execute Pop-up handling code when Pop-up is opened because when I close the Pop-up manually then only this Pop-up handling code executes not at the time when Pop-up is opened.
Please let me know if question doesn't provide satisfactory information.
Thanks
Try Using Alert class or PopupWindowFinder Code in the link is based on c#, i hope you can convert it to your desired language easily
popup's in selenium webdrivers

Unable to handle the new window

I have a situation(mentioned below) due to which my selenium script is failing. Can someone help me?
I have a webpage where there is a save button, clicking on save button opens a new popup window. My requirement is to switch to the new window and click on one of the buttons(in the new window) which will automatically close the window and navigates to some other page. I have written a code which actually works fine but sometimes due to the application problem the new window is not getting closed. And due to this my script is failing. Here is the code I have used.
public void test() {
// i have two pages gets involved in this scenario
driver.get("some url"); // user is in page 1
// clicking on save button
driver.findElement(By.xpath("some xpath")).click(); // a new window opens
Set<String> winIDS = driver.getWindowHandles();
if (winIDS.size() > 1) {
Iterator<String> it = winIDS.iterator();
it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);
driver.findElement(By.xpath("some xpath")).click();
//after clicking on this button the user is navigated to page2
}
// after clicking on the button in the new window the new window gets closed and the user is navigate to page 2 as mentioned before.
// To validate if that has happened i am using the below code so that my test case flow wont be stopped. But
// the code is getting hanged at the new window as the app fails to perform the button click action on the new window.
winIDS = driver.getWindowHandles();
if(winIDS.size() > 1)
{
Iterator<String> it = winIDS.iterator();
it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);
driver.close();
//i m making the test failed here as the new window is not closed.
}
}
Looking at your code, I can see that you do twice the iteration to next window:
it.next();
String childWindow = **it.next();**
The second it.next() is obsolet.
Hope this solvs your issue.

File Upload button is not working using Selenium webdriver

Am trying to upload a jpeg image to my application . But on webpage we can upload other jpeg images as well in their respective section. Here as per the HTML, Upload button have the same attributes defined for other upload sections.
However ,When I inspect the xpath for Unique element for Upload button , I found the below xpath=//table/tbody/tr[1]/td[1]/div/div/div/input[#class='bttnUpload'] and verified using xpath checker
Below is Webdriver code used
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//Test URL
driver.get("URL");
// UN & PWD
driver.findElement(By.xpath("//input[#id='UserName']")).clear();
driver.findElement(By.xpath("//input[#id='UserName']")).sendKeys("UN");
driver.findElement(By.xpath("//input[#id='Password']")).clear();
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys("pwd");
driver.findElement(By.xpath("//input[#id='btnSubmit']")).click();
//Validate the User logged in
if(driver.getPageSource().contains("UN Kumar"))
System.out.println("UN is logged in");
else
System.err.println("UN not logged in");
//Click on Asset Menu and LookUp Assets sub menu
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//a[#href='http://ccqweb1.cloudapp.net//Main.aspx? MenuId=15']"))).build().perform();
driver.findElement(By.linkText("Lookup Assets")).click();
//Search for Loan Number
driver.findElement(By.xpath("//input[#id='ctl10_txtLoannumber']")).sendKeys("787878717");
driver.findElement(By.xpath("//input[#id='ctl10_cmdSearch']")).click();
Thread.sleep(2000);
// Get the window handle before clicking on link
String winHandleBefore = driver.getWindowHandle();
//Click on Initial Occupancy task
driver.findElement(By.xpath("//a[#id='ctl09_gvPendingTasks_ctl02_lnkTask']")).click();
Thread.sleep(2000);
// Switch to New Window
String child = driver.getWindowHandle();
for(String parent : driver.getWindowHandles()){
driver.switchTo().window(parent);
}
/**Exterior Photos tab **/
//Click on Exterior tab
driver.findElement(By.xpath("//a[#id='ctl09_btnExteriorPhotos']")).click();
//Front View* `enter code here`
//Click on Manual Upload button
driver.findElement(By.xpath("//div/input[#onclick='DisplayManualUpload(event)']")).click();
WebElement FileUpload_FrontView= driver.findElement(By.xpath("//input[#class='fleManuleUpload']"));
FileUpload_FrontView.sendKeys("\\Front_view.jpeg");
Thread.sleep(500);
driver.findElement(By.xpath("//table/tbody/tr[1]/td[1]/div/div/div/input[#class='bttnUpload']")).click();
The Upload image is getting selected but Upload button not is clicked so am not able to upload the file.
Can you help me to solve this ?
I'm pretty sure it's just a typo.
As well as for the upload locator
(//input[#class='fleManuleUpload'] ->e.g. fleManualUpload )
as for the upload button
([#class='bttnUpload'] -> btnUpload ).
In General: Why don't you use more consistent css locators or just ids?
By.xpath("//input[#id='UserName']"
use easily:
By.id("UserName")
To give you a better answer please upload the error message when you run this.
The reason behind this is:
FileUpload_FrontView.sendKeys("C:\\Users\\prabhakar.y\\Desktop\\Pics for Uploading\\Front_view.jpeg");
You are having space in foldername - "Pics for Uploading".
Try out by giving
File f = new File("Pics for Uploading\\Front_view.jpeg");
FileUpload_FrontView.sendKeys(f.getAbsolutePath());
and this folder should be inside your current workspace (Its a good practice). Or else remove space from foldername.

Selenium webdriver: Unable to send keys In a new popup window

Using selenium web-driver I am trying to put region name In the text box In new popup screen and click on save button. I using the below script for that
String mainWindowHandle1=driver.getWindowHandle();
driver.switchTo().window(mainWindowHandle1 );
driver.findElement(By.id("MainContent_imgAddRegion")).click();
Thread.sleep(5000);
java.util.Set<String> s1 = driver.getWindowHandles();
Iterator<String> ite1 = s1.iterator();
while(ite1.hasNext())
{
String popupHandle=ite1.next().toString();
if(!popupHandle.contains(mainWindowHandle1))
{
driver.switchTo().window(popupHandle).findElement(By.id("txtRegionName")).sendKeys("South Region");
Thread.sleep(3000);
driver.findElement(By.id("txtRegionName")).sendKeys("South Region");
Thread.sleep(1000);
driver.findElement(By.id("btnSave")).click();
By doing this I am able to open the new popup screen to enter the region but, I am unable to send keys [region name] and save the text.Even I am not getting any failed report when I run the test.
This may be due to iFrames presence.
Look in the HTML code and check if the text field that you are trying to send keys to and the save button are included in some sort of iFrame.
If so, you will need to do something like:
driver.switchTo().defaultContent();
driver.switchTo().frame("framename");
driver.findElement(By.id("txtRegionName")).sendKeys("South Region");
driver.findElement(By.id("btnSave")).click();
Hope it helps!

Resources