Issue facing in Selenium handling multiple window - java

I have written the below script where first i will click on FACEBOOK Sign in button then the pop up for FACEBOOK login page will open in a separate window.I am entering the id and password. But my issue is when i am clicking on the login button then that window will disappear and my parent window URL will change. How to handle the changed URL. I need to perform some operation on that. I am aware that i can move to parent window,but the issue is when i click on login the URL changes
private void facebookSignIn(){
WebElement element=null;
try{
element = driver.findElement(By.xpath(".//*[#id='signin_facebook_button']/div[2]"));
String mwh=driver.getWindowHandle();
element.click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
Set<String> set=driver.getWindowHandles();
Iterator<String> iterator=set.iterator();
while(iterator.hasNext())
{
String popupHandle=iterator.next().toString();
if(!popupHandle.contains(mwh))
{
driver.switchTo().window(popupHandle);
element = driver.findElement(By.xpath(".//*[#id='email']"));
element.sendKeys(account);
element = driver.findElement(By.xpath(".//*[#id='pass']"));
element.sendKeys(password);
element = driver.findElement(By.xpath(".//*[#id='u_0_2']"));
countDownLatch.countDown();
countDownLatch.await();
element.click();
System.out.println("Click Done");
//driver.switchTo().window(mwh);
}
}
start = System.currentTimeMillis();
counter++;
if(counter==1)
{
startTime=System.currentTimeMillis();
}
#SuppressWarnings("unused")
WebElement sso_logout = (new WebDriverWait(driver,30)).until(ExpectedConditions.visibilityOfElementLocated(By.id("sso_logout")));
end = System.currentTimeMillis();
endTime=System.currentTimeMillis();
try{
element = driver.findElement(By.id("sso_logout"));
element.click();
}
catch(Exception e)
{
System.out.println("Exception from SSO_Logout");
}
double temp=(double)(end-start)/1000;
latencyMap.put(Thread.currentThread().getName(),temp) ;
System.out.println(Thread.currentThread().getName()+"-->Done");
}
catch(Exception e){
countDownLatch.countDown();
totalNumberOfUsers--;
System.out.println(account);
System.out.println(e.getMessage());
}
}

WindowHandle is not based on url, so it shouldn't effect you. If you need to switch back do something like that:
String parentHandle = driver.getWindowHandle();
// switch to the new window
for (String winHandle : driver.getWindowHandles()) {
if (!winHandle.equals(parentHandle))
{
driver.switchTo().window(winHandle);
}
}
//do something with the new window
element = driver.findElement(By.xpath(".//*[#id='email']"));
element.sendKeys(account);
element = driver.findElement(By.xpath(".//*[#id='pass']"));
element.sendKeys(password);
element = driver.findElement(By.xpath(".//*[#id='u_0_2']"));
countDownLatch.countDown();
countDownLatch.await();
element.click();
System.out.println("Click Done");
// switch back to the old window
driver.switchTo().window(parentHandle);
// if the new window is closed by its on
driver.switchTo().window(driver.getWindowHandle());
WindowHandle example:
"CDwindow-0D7BB6F6-A7E0-4DCE-B4D0-F202E85D982D"

Related

How to assert Listing data which is having lazy loading in selenium java

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
After using this it will load more 20 records till list is not getting ended so how I can get the hall list size and how I can print the hall list data
You can use like:
First Approach By pressing ctrl+end
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.END);
Second Approach : By using Java Robot class
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_CONTROL);
OR you can use the below by extending your code
try {
Object lastHeight = ((JavascriptExecutor) driver).executeScript("return document.body.scrollHeight");
while (true) {
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
Thread.sleep(2000);
Object newHeight = ((JavascriptExecutor) driver).executeScript("return document.body.scrollHeight");
if (newHeight.equals(lastHeight)) {
break;
}
lastHeight = newHeight;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

My Wait() method works in 'Chrome' & 'Firefox' but not in 'IE'?

My Wait() method works in 'Chrome' & 'Firefox' but not in 'IE', any ideas?
I have tried using IEDriverServer.exe both the 32bit and the 64bit(Send keys acts slow), but the following method still dosnt click on the intended target.
Please note: I know the locators are fine as listed above works in both Chrome and firefox.
public void waitAndClickFirstDrivingExperiencesOption(WebElement element) throws Exception {
WebDriverWait wait2 = new WebDriverWait(driver, 30);
Base_Page basePage = new Base_Page(driver);
try {
System.out.println(basePage.browser_type);
Boolean elementPresent = wait2.until(ExpectedConditions.elementToBeClickable(element)).isEnabled();
if (elementPresent == true) {
if (!this.browser_type.equals("firefox")) {
// Provide a slight timeout before clicking on the element
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
basePage.actionMoveAndClick(element);
} else {
Thread.sleep(500);
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
element.click();
}
}
System.out.println("Clicked on the first supercars link, using locator: " + element.toString());
} catch (StaleElementReferenceException elementUpdated) {
element = this.driver.findElement(By.xpath(".//*[#id='prd_listing']/div/li[1]/a"));
Boolean elementPresent = wait2.until(ExpectedConditions.elementToBeClickable(element)).isEnabled();
if (elementPresent == true) {
if (!this.browser_type.equals("firefox")) {
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
basePage.actionMoveAndClick(element);
} else {
Thread.sleep(500);
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
element.click();
}
}
System.out.println(
"Clicked on the first supercars link (Stale Exception), using locator: " + element.toString());
} catch (Exception e) {
System.out.println("Exception! - could not click on the first supercars link, Exception: " + e.toString());
throw (e);
} finally {
}

How can I change try catch exception to WebDriverWait

I am trying to login and search records based on date selected from a calendar. I have used try catch exception after each step. I need to replace try catch with WebDriverWait. But the problem is that I have fields on the page which are getting identified by id or XPath. So I am not getting a way out how to implement WebDriverWait instead of try catch. Can anyone help me out? Below is my code structure with details.
public class Login {
public static WebDriver driver;
String username = "username";
String password = "password";
String baseurl = "http://mybusiness.com/login.aspx";
public class Details {
#Test(priority = 0)
public void loginpage() {
//WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.chrome.driver","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
capabilities.setCapability("chrome.binary","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement password = driver.findElement(By.id("Password"));
password.sendKeys(password);
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement button = driver.findElement(By.id("ButtonClick"));
button.click();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
// Selecting a date from date picker
#Test(priority = 1)
public void RecordSearch() {
WebElement calendar = driver.findElement(By.id("CalendarId"));
calendar.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement month = driver.findElement(By.xpath("XPath"));
month.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement day = driver.findElement(By.xpath("XPath"));
day.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement submit = driver.findElement(By.id("Submit"));
submit.click();
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
driver.close();
}
I would have thought you'd be better off adding an implicit wait, e.g. once you've setup your driver object add the following line:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
A simple example would take your code
try
{
Thread.sleep(10000); // 1000 milliseconds is one second.
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
and change it to
String username = "username123";
WebDriverWait wait = new WebDriverWait(driver, 10); // 10 seconds
WebElement usernameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("UserName")));
usernameField.sendKeys(username);
Once you have defined wait, you can reuse it over and over and it will have the same attributes, e.g. 10 sec wait time.
String password = "abc123";
WebElement passwordField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Password")));
passwordField.sendKeys(password);
NOTE: I noticed that you were using username.sendKeys(username);. I'm assuming/hoping this isn't actual code since .sendKeys() takes a String and you have username defined as a WebElement. I fixed it in my code and named the two differently.
There is WebDriverWait functionality in selenium, you can set explicit wait. You are using selenium webdriver, then it is far better to use WebDriverWait for waiting purpose to element. follow below code
protected WebElement waitForPresent(final String locator, long timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement ele = null;
try {
ele = wait.until(ExpectedConditions
.presenceOfElementLocated(locator));
} catch (Exception e) {
throw e;
}
return ele;
}
protected WebElement waitForNotPresent(final String locator, long timeout) {
timeout = timeout * 1000;
long startTime = System.currentTimeMillis();
WebElement ele = null;
while ((System.currentTimeMillis() - startTime) < timeout) {
try {
ele = findElement(locator);
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
return ele;
}
Whenever you require wait for element present, call waitForPresent method with expected parameters.
If you explore little, you can find different types of WebDriverWait. One of the most common is WebDriver.wait(timeinmilliseconds).
and for example, others are,
webDriver.waituntil (Expectedconditions)...
wait.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.className("sel"));
String enabled = button.getText();
return enabled.contains(city);
}
});
or for example
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("froexample_username_txtbox")));
PS : define private final WebDriverWait wait;
It may be more useful if you are not sure about implict timewait value.(be being specific about events and results)

ElementNotVisibleException error

I'm trying to expand all comments, replies, see more in comment, and see more in post in Facebook.
1) The codes I have written below allows me to expand all contents that I want except for maybe a few replies in a post even though I have put the repliesbutton in a loop.
2) There will a Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with error at the .click() if there is no try-catch in all the smaller for loops.
//declare WebDriverWait variable, times out after 20 seconds
WebDriverWait wait = new WebDriverWait(dr, 20);
//check element is present on the DOM of a page and visible
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("commentable_item")));
List<WebElement> comments = dr.findElements(By.className("commentable_item")); //get the comments
//iterate through the comments
for (WebElement comment : comments) {
boolean clickMore = true;
try {
while(clickMore == true) {
//find web elements by their respective class name
List<WebElement> commentsbutton = comment.findElements(By.className("UFIPagerLink")); //view more/previous comments
List<WebElement> repliesbutton = comment.findElements(By.className("UFIPagerIcon")); //replies
List<WebElement> seemorebutton = comment.findElements(By.className("_5v47")); //see more in comment
List<WebElement> seemorelinkbutton = dr.findElements(By.className("see_more_link")); //see more in link
//click more comments
if(commentsbutton.size() > 0) {
for (WebElement comments_element : commentsbutton) {
//comments_element.click(); //click on button if found
//Thread.sleep(5000); //pause for 5 seconds
try{
comments_element.click(); //click on button if found
Thread.sleep(5000); //pause for 5 seconds
} catch(Exception e){
}
}
for (WebElement replies_element : repliesbutton) {
//replies_element.click(); //click on button if found
//Thread.sleep(3000); //pause for 3 seconds
try{
replies_element.click(); //click on button if found
Thread.sleep(3000); //pause for 5 seconds
} catch(Exception e){
}
}
}
else clickMore = false;
for (WebElement seemorelinks_element : seemorelinkbutton) {
try{
seemorelinks_element.click(); //click on button if found
Thread.sleep(5000); //pause for 5 seconds
} catch(Exception e){
}
}
for (WebElement seemore_element : seemorebutton) {
try{
seemore_element.click(); //click on button if found
Thread.sleep(5000); //pause for 5 seconds
} catch(Exception e){
}
}
}
} catch (NoSuchElementException e) { //when no elements are found
System.out.println("Comments in this post not found");
}
}
}
//return the given element if it is visible and has non-zero size, otherwise null.
private static WebElement elementIfVisible(WebElement element) {
return element.isDisplayed() ? element : null;
}
public static ExpectedCondition<WebElement> visibilityOfElementLocated(final By locator) {
return new ExpectedCondition<WebElement>() {
#Override
public WebElement apply(WebDriver driver) {
try {
return elementIfVisible(dr.findElement(locator));
} catch (StaleElementReferenceException e) {
return null;
}
}
};
}
}
You can create a utility method and put it in some 'Utility.java' class something like below:
public void click(WebElement element)
{
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
if(element.isDisplayed())
element.click();
}
Usage:
WebElement element=driver.findElement(//Locator);
Utility.click(element);
This will ensure every time before you click the element is scrolledIntoView.
Let me know if you need further help on this.

How to reset the name of user in the field?

There is a table list of username, from these table I have edited the username "Pra" to "Pra1", but now when I come to the user table list its not finding a user with the name "Pra" because its updated with "Pra1".
So, what I want is after updating an username in the search filter it search with updated username (With "Pra1").
Below are the running code upto the updated username please help me after that:
public class InsSystemCenter {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("URL");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Verify the insfocus system center page has been opened or not by
// xpath//
if (driver.findElement(By.xpath("/html/body/table/tbody/tr[1]/td/h1")) != null) {
System.out.println("Center has been opened");
} else {
System.out.println("Center is not displaying");
}
WebElement userName = driver.findElement(By.name("username"));
userName.sendKeys("pra");
WebElement password = driver.findElement(By.name("password"));
password.sendKeys("123456");
WebElement signIn = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[2]/td/table/tbody/tr[1]/td/form/center/div/table/tbody/tr[4]/td/input"));
signIn.click();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Verify that welcome page is displayed or not//
WebElement welcomePageVerify = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div[2]/span"));
if (welcomePageVerify.isDisplayed()) {
System.out.println("Welcome page is displaying");
} else {
System.out.println("Welcome page is not displaying");
}
// Try to click on the tab name "Settings" by xpath//
WebElement settings = driver.findElement(By
.xpath("/html/body/table/tbody/tr[2]/td/ul/li[3]/a"));
settings.click();
// Verifying that after clicking on "Setting" it opens a database page
// or not//
WebElement settingsVerify = driver
.findElement(By
.xpath("/html/body/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]/h1/span"));
if (settingsVerify.isDisplayed()) {
System.out
.println("Database page is displayed after clicking on Setting tab");
} else {
System.out.println("Database page is not displaying");
}
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Click on the button "Users" by xpath, so that it goes to the page
// where it show the list of users //
WebElement users = driver
.findElement(By
.xpath("/html/body/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[1]/p/a[2]"));
users.click();
// Verifying for users page opened or not//
WebElement usersPageVerify = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]/h1"));
if (usersPageVerify.isDisplayed()) {
System.out
.println("Users page is displayed after clicking on users button");
} else {
System.out.println("Users page is not displaying");
}
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
System.out.println("Total time take " + new Date());
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
System.out.println("Total time take " + new Date());
WebElement usUserName = driver.findElement(By.id("g_UserName"));
usUserName.sendKeys("Pra");
usUserName.sendKeys(Keys.ENTER);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
usUserName.sendKeys(Keys.TAB);
System.out.println("Total time take " + new Date());
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
// Checked the checkbox of find elemet or user//
WebElement checkbox = driver.findElement(By.id("jqg_tblMainTable_243"));
checkbox.click();
// After checked the checkbox it enables the edit button for edit the
// user//
WebElement editButton = driver.findElement(By.id("btnEdit"));
editButton.click();
// ------------Edit user popup--------------//
// Verify edit popup opened or not//
String source = driver.getPageSource();
int a = source.indexOf("Edit User:");
if (a > 0) {
System.out.println("Edit user popup is displayed");
} else {
System.out.println("Edit user popup is not displaying");
}
// All the WebElement parameter is located here//
WebElement euUserName = driver.findElement(By.id("UserName"));
euUserName.clear();
euUserName.sendKeys("pra1");
WebElement euFullName = driver.findElement(By.id("txtFullName"));
euFullName.clear();
euFullName.sendKeys("pra1");
WebElement euPassword = driver.findElement(By.id("txtPassword"));
euPassword.sendKeys("123456");
WebElement euConfirmPassword = driver.findElement(By
.id("txtConfirmPassword"));
euConfirmPassword.sendKeys("123456");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
WebElement dropdown = driver.findElement(By.id("RoleID"));
// Verify dropdown is displayed or not not //
if (dropdown.findElement(By.id("RoleID")) != null) {
System.out.println("Dropdown is displayed");
} else {
System.out.println("Dropdown is not displaying");
}
Select clickThis = new Select(dropdown);
clickThis.selectByVisibleText("Normal");
System.out.println("Drop down values "+clickThis.getOptions().get(0).getText());
WebElement euUserDetail = driver.findElement(By.id("UserDetails"));
euUserDetail.clear();
euUserDetail.sendKeys("pra1");
WebElement euOk= driver.findElement(By.xpath("/html/body/div[3]/div[3]/div/button[1]"));
euOk.click();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
driver.quit();
}
}
Just call clear() method before your calling sendKeys("your text").
This should work.
Just use the clear function before passing the value to the webelement
WebElement userName = driver.findElement(By.name("username"));
userName.clear();
userName.sendKeys("pra");
Same way you can use for all the elements.
ok i can't even be bothered trying to read a 7 million line long main method
1) refactor it in to separate logical methods (responsibility driven design)
2) when you have done that post us the code responsible for your issues
3) maybe look at assigning the value you want to search on to a temporary variable so you can find it again?

Categories

Resources