Webdriver : How to switch to a specific window? - java

I came across many solutions for switching between windows, one of them is:
Set<String> allWindows = driver.getWindowHandles();
for(String currentWindow : allWindows){
driver.switchTo().window(currentWindow);
}
But, I am unable to go to a particular window. Can someone tell me how to switch to 3rd window from parent window (using java client library)?

You are almost there. If you want to switch to a window first store the window id's in an array and switch to some specific window. Some thing like below. Let me know if you want more help. Happy coding.
Set handles = driver.getWindowHandles();
String[] individualHandle = new String[handles.size()];
Iterator it = handles.iterator();
int i =0;
while(it.hasNext())
{
individualHandle[i] = (String) it.next();
i++;
}
driver.switchTo().window(individualHandle[1]);

public static void switchWindow(String text) {
WebDriver popup = null;
Iterator<String> windowIterator = driver.getWindowHandles()
.iterator();
while (windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = driver.switchTo().window(windowHandle);
String title = popup.getTitle();
if (title.contains(text)) {
break;
}
}
}
This will get you any window that contains certain text, you don't have to be specific.

The below method will navigate to a particular window
public static void switchToParticularWindow(WebDriver driver, int index) throws InterruptedException {
ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(tabs.get(index));
Thread.sleep(2000);
logger.info("Switched to new tab");
}

public class WindowHandles {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://www.way2automation.com/lifetime-membership-club/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[#id=\"menu-item-25089\"]/a/span[2]")).click();
driver.findElement(By.xpath("//*[#id=\"ast-desktop-header\"]/div[1]/div/div/div/div[2]/div/div/div/a[1]")).click();
Set<String> window = driver.getWindowHandles();
Iterator<String> it =window.iterator();
while(it.hasNext())
{
String childWindow = it.next();
String windowTitle = driver.switchTo().window(childWindow).getTitle();
if(windowTitle.contains("Way2Automation"))
{
break;
}
}
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//*[#id=\"blueBarDOMInspector\"]/div/div/div/div[1]/a")).click();
System.out.println(driver.getTitle());
}
}

Related

How to use explicit wait condition with selenium 4.0

using Java 17 and slenium 4.0
wait.until(ExpectedConditions.titleContains("BrowserStack"));
here is full code :
public class mainTestClass {
public static final String USERNAME = "myuser *****";
public static final String AUTOMATE_KEY = "my ke *****";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
public static void main(String[] args) throws Exception {
Thread object1 = new Thread(new TestClass1());
object1.start();
Thread object2 = new Thread(new TestClass2());
object2.start();
Thread object3 = new Thread(new TestClass3());
object3.start();
}
public void executeTest(Hashtable<String, String> capsHashtable) {
String key;
DesiredCapabilities caps = new DesiredCapabilities();
// Iterate over the hashtable and set the capabilities
Set<String> keys = capsHashtable.keySet();
Iterator<String> itr = keys.iterator();
while (itr.hasNext()) {
key = itr.next();
caps.setCapability(key, capsHashtable.get(key));
}
WebDriver driver;
try {
driver = new RemoteWebDriver(new URL(URL), caps);
JavascriptExecutor jse = (JavascriptExecutor)driver;
// Searching for 'BrowserStack' on google.com
driver.get("https://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
// Setting the status of test as 'passed' or 'failed' based on the condition; if title of the web page contains 'BrowserStack'
WebDriverWait wait = new WebDriverWait(driver, 5);
try {
// wait.until(ExpectedConditions.titleContains("BrowserStack"));
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Title matched!\"}}");
}
catch(Exception e) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Title not matched\"}}");
}
System.out.println(driver.getTitle());
driver.quit();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
This is cause in Selenium 4.0.0 (Stable)
WebDriverWait which takes driver and timeoutInSeconds long, have been Deprecated
#Deprecated
public WebDriverWait(WebDriver driver, long timeoutInSeconds) {
this(driver, Duration.ofSeconds(timeoutInSeconds));
}
Fix:
Selenium devs have given this method instead
public WebDriverWait(WebDriver driver, Duration timeout) {
this(
driver,
timeout,
Duration.ofMillis(DEFAULT_SLEEP_TIMEOUT),
Clock.systemDefaultZone(),
Sleeper.SYSTEM_SLEEPER);
}
so your effective code will be :
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
wait.until(ExpectedConditions.titleContains("BrowserStack"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
}
catch(Exception e) {
e.printStackTrace();
}

How to test sublinks on a page in Selenium

How to test sub links on a page in Selenium. I have an events page. Then from that events page i collect all the different events links. Then i want to recursively run tests on those links.
I have attached an image of the page. The green text are all links. So i collected the href values of all these. After that I have some tests to run on those pages. I have a test class called EventsPageTest for the main page. The test class for the sub pages is called SingleEventsPageTest. How do I transfer the href values from the main class to the other class. Or is there any other method I need to follow.
I searched the internet so much but was of no use.
Any help would be appreciated.
Thanks
EventsPageTest
package test;
import pages.EventsPageObjects;
#Listeners(listeners.TestListener.class)
public class EventsPageTest {
private static ExtentHtmlReporter htmlReporter;
private static ExtentReports extent;
private static ExtentTest test;
static WebDriver driver = null;
private static EventsPageObjects eventsPage;
public MutableCapabilities capabilities;
static Set<String> eventsLinks = new HashSet<String>();
String url;
#BeforeSuite
public void setUp() {
// initialize the HtmlReporter
htmlReporter = new ExtentHtmlReporter("extentReportsEventsPage.html");
// initialize ExtentReports and attach the HtmlReporter
extent = new ExtentReports();
// attach only HtmlReporter
extent.attachReporter(htmlReporter);
}
#BeforeTest
public void setUpTest() throws IOException{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
url = "abc.com";
driver.get(url);
System.out.println("Inside setUpTest");
//Create eventsPageObject
eventsPage = new EventsPageObjects(driver);
}
#Test(alwaysRun=true)
public void collectEventsLinks() throws InterruptedException, IOException {
test = extent.createTest("Collect all Events Links on a page","Test to Collect all Events Links on a page ");
test.log(Status.INFO, "Starting Test Case");
List<WebElement> links = driver.findElements(By.tagName("a"));
for (int i = 0; i<links.size(); i++) {
if(Pattern.matches("^https://"+ TestRunner.url +"/events/[^/]+[^\\s]$", links.get(i).getAttribute("href")))
eventsLinks.add((links.get(i).getAttribute("href")));
}
test.log(Status.INFO, "Finished Test Case");
}
#AfterTest(alwaysRun = true)
public void tearDownTest() {
//close browser
driver.close();
driver.quit();
}
#DataProvider(name="getURLS")
#AfterTest
public Object[] getURLS() {
System.out.println("Inside get Urls");
System.out.println("getURLS : " + eventsLinks.size());
Object[] objArray = eventsLinks.toArray();
System.out.println(eventsLinks.size());
return objArray;
}
#AfterSuite
public void tearDown() {
extent.flush();
}
}
SingleEventsPageTest
package test;
#Listeners(listeners.TestListener.class)
public class SingleEventsPageTest{
private static ExtentHtmlReporter htmlReporter;
private static ExtentReports extent;
private static ExtentTest test;
static WebDriver driver;
private static SingleEventsPageObjects singleEventsPage;
static List<Object> eventsURLS = new ArrayList<Object>();
#BeforeSuite
public void setUp() {
PropertiesFile.getProperties();
// initialize the HtmlReporter
htmlReporter = new ExtentHtmlReporter("extentReportsSingleEventsPage.html");
// initialize ExtentReports and attach the HtmlReporter
extent = new ExtentReports();
// attach only HtmlReporter
extent.attachReporter(htmlReporter);
}
#BeforeTest
public void setUpTest() throws IOException{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
//Create eventsPageObject
singleEventsPage = new SingleEventsPageObjects(driver);
}
#Test(dataProvider="getURLS",dataProviderClass=EventsPageTest.class,alwaysRun=true)
public void findIfEventsTitleExists(String url) throws InterruptedException, IOException {
driver.get(url);
System.out.println("Inside findIfEventsTitleExists : " + driver.getCurrentUrl());
test = extent.createTest("Events Title Exists","Test to verify if the Events Title exists after opening the page");
test.log(Status.INFO, "Starting Test Case");
test.log(Status.INFO, "Checking If the URL points to the events page else navigate to that");
Assert.assertEquals(true,singleEventsPage.findIfEventsTitleExists());
test.log(Status.INFO, "Finished Test Case");
}
#Test(dataProvider="getURLS",dataProviderClass=EventsPageTest.class,alwaysRun=true)
public void verifyIfEventDescriptionExists(String url) throws InterruptedException, IOException {
driver.get(url);
test = extent.createTest("Events description Exists","Test to verify if the Events description exists");
test.log(Status.INFO, "Starting Test Case");
test.log(Status.INFO, "Checking If the URL points to the events page else navigate to that");
if(singleEventsPage.getCurrentUrl() != url)
singleEventsPage.navigateTo(url);
test.log(Status.INFO, "Checking If the Page Sub Title Exists");
Assert.assertEquals(true,singleEventsPage.checkIfElementExists(singleEventsPage.getEventDesc()));
test.log(Status.INFO, "Finished Test Case");
}
#AfterTest(alwaysRun = true)
public void tearDownTest() {
//close browser
driver.close();
driver.quit();
}
#AfterSuite
public void tearDown() {
extent.flush();
}
}
It would be good if you could post your code here. You can try to store them in one class as List, then pass them to another.
I am not sure how your framework is working now. I am thinking of something like this. Please post more code here.
class EventsPageTest {
public List<T> getAllHref() {
// return List
}
}
class SingleEventsPage {
#Test
public void someTest () {
EventsPageTest eventsPageTest = new EventsPageTest();
List<T> hrefs = eventsPageTest.getAllHref();
}
}
Hope this helps

Cannot handle pop-up windows consistently

I have a tricky situation:
I am handling two popups after entering login info, but on the second pop-up I am not able to consistently hit the OK button every time
I have tried Waits, Storing Element in List and Switch cases
public class loginUser {
public static WebDriver driver = new InternetExplorerDriver();
public static void winHandles()
{
String newHandle = null;
Set<String> newHandles = driver.getWindowHandles();
Iterator<String> itr = newHandles.iterator();
while(itr.hasNext()){
newHandle = itr.next();
driver.switchTo().window(newHandle);
System.out.println(driver.getCurrentUrl());
}
}
public static void main(String args[]) throws InterruptedException
{
System.setProperty("","");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("");
driver.findElement(By.name("")).sendKeys("");
driver.findElement(By.name("")).sendKeys("");
driver.findElement(By.name("")).sendKeys("");
driver.findElement(By.id("")).click();
String parentWindowHandler = driver.getWindowHandle();
winHandles();
List<WebElement> yesbutton = driver.findElements(By.id("btnYes"));
for (int i = 0; i < 4; i++) {
if(yesbutton.get(0).isDisplayed())
{
yesbutton.get(0).click();
}
else {
System.out.println("button is creating problems");
}
}
driver.switchTo().window(parentWindowHandler);
System.out.println(driver.getCurrentUrl());
winHandles();
Thread.sleep(3000);
List<WebElement> okbutton = driver.findElements(By.id("btnOK"));
for (int i = 0; i < 4; i++) {
if(okbutton.get(0).isDisplayed())
{
okbutton.get(0).click();
}
else {
System.out.println("button is creating problems");
}
}
Thread.sleep(7000);
winHandles();
driver.findElement(By.name("")).click();
driver.findElement(By.id("")).click();
driver.findElement(By.name("")).click();
driver.findElement(By.id("")).click();
driver.findElement(By.name("")).click();
driver.close();
}}
So, this is the hard coded version
The locator with id btnOK is causing problems mostly.
Like 4 out of 5 times
I also have the same kind of issue while running test in firefox but in chrome, test runs successfully. You can use try catch :
try
{
okbutton.get(0).click();
}
catch(Exception e)
{
}
This is not advisable but due to browser compatibility, i had to use this as a temporary solution.If anyone has real solution kindly update me too...

Not able to get links of all the total pages

I'm trying to type selenium in google and get all the title text of result in a notepad file. i want to get all available links on all the pages, till last page of search. but only 1st page's link i am getting. when i debug and run, it is working for some 10 pages.help me in this.
JAVA code:
public class weblink
{
public static void main(String[] args) throws IOException, InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "E:\\disha.shah/myWork/eclipse/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
PrintStream ps = new PrintStream(new File(("E:\\disha1.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//*[#id='rso']//h3/a"));
for (WebElement webElement : findElements)
{
System.out.println("-" + webElement.getText()); // for title
//System.out.println(webElement.getAttribute("href")); // for links
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
System.setOut(ps);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
Thread.sleep(1000);
if(driver.findElement(By.linkText("Next")).isDisplayed()== true)
{
driver.findElement(By.linkText("Next")).click();
}
else
{
System.out.println("All Link is Covered");
}
}
while(driver.findElement(By.linkText("Next")).isDisplayed() );
{
//Thread.sleep(2000);
}
}
}
I've done some correction. the updated code is below.-
public static void main(String[] args) throws IOException, InterruptedException
{
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "D:/Application/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
Boolean nextButtonFlag = true;
// Create two separate file storing the result
PrintStream searchTitle = new PrintStream(new File(("D:\\Titles.txt")));
PrintStream searchLink = new PrintStream(new File(("D:\\Links.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for (WebElement element : findElements)
{
// Write all received links and title inn txt file
searchTitle.append(element.getText()+"\n");
searchLink.append(element.getAttribute("href")+"\n");
}
Thread.sleep(2000);
try
{
driver.findElement(By.linkText("Next")).click();
}
catch(Exception e)
{
// no more next button to navigate further link
nextButtonFlag=false;
}
Thread.sleep(2500);
}
while(nextButtonFlag);
System.out.println("Execution done");
searchTitle.close();
searchLink.close();
}
}

Unable to switch between frames in WebDriver

I am working on contacts creation page in www.salesforce.com developer login account. Anybody can create a free developer login account and access this page.
I am unable to switch between frames in Lookup window. There are two frames, one is search frame with textbox and button to search and below that is results frame for displaying search results with hyperlinks for selection. I am specifying the frames by frame name or id, but webDriver switches to search frame and does the searching but then is not able to locate the results frame with NoSuchFrameException.
If I do not switch to search frame initially but directly switch to results frame, it is indeed successful in the locating the results frame which displays results of some recent searches done by default.
How do I switch from search frame to results frame ? Given below is my code
public class Acc_Parent
{
WebDriver driver;
FileInputStream fis;
XSSFWorkbook wb;
XSSFSheet sh;
#Test
public void createParent() throws IOException, InterruptedException, FileNotFoundException
{
driver = new FirefoxDriver();
//System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
//driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://test.salesforce.com");
fis = new FileInputStream("C:/Users/psit/Documents/Login.xlsx");
wb = new XSSFWorkbook(fis);
sh = wb.getSheetAt(0);
driver.findElement(By.xpath(".//*[#id='username']")).sendKeys(sh.getRow(1).getCell(0).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='password']")).sendKeys(sh.getRow(1).getCell(1).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='Login']")).click();
fis = new FileInputStream("C:/Users/psit/Documents/Input.xlsx");
wb = new XSSFWorkbook(fis);
sh = wb.getSheet("Parent");
driver.findElement(By.xpath(".//*[#id='Account_Tab']/a")).click();
driver.findElement(By.xpath(".//*[#id='hotlist']/table/tbody/tr/td[2]/input")).click();
driver.findElement(By.xpath(".//*[#id='j_id0:acctFrm:nmsrch']")).sendKeys(sh.getRow(1).getCell(1).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='j_id0:acctFrm']/div[1]/div[2]/table/tbody/tr/td[2]/input")).click();
try
{
driver.findElement(By.linkText("click here")).click();
driver.findElement(By.xpath(".//*[#id='parentAcc']")).sendKeys(sh.getRow(1).getCell(1).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='childAcc']")).sendKeys(sh.getRow(1).getCell(2).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:0:actFields']")).sendKeys(sh.getRow(1).getCell(3).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:2:actFields']")).sendKeys(sh.getRow(1).getCell(4).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:4:actFields']")).sendKeys(sh.getRow(1).getCell(5).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:6:actFields']")).sendKeys(sh.getRow(1).getCell(6).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:8:actFields']")).sendKeys(Integer.toString((int)sh.getRow(1).getCell(7).getNumericCellValue()));
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:1:actFields']")).sendKeys(sh.getRow(1).getCell(8).getStringCellValue());
Thread.sleep(2000);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:3:actFields']")).sendKeys(sh.getRow(1).getCell(9).getStringCellValue());
String mainWindow = driver.getWindowHandle();
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:5:actFields_lkwgt']/img")).click();
Thread.sleep(5000);
Set<String> winhand = driver.getWindowHandles();
for(String str : winhand)
{
if(!str.equalsIgnoreCase(mainWindow))
{
driver.switchTo().window(str);
break;
}
}
try
{
driver.switchTo().frame("searchFrame");
driver.findElement(By.xpath(".//*[#id='lksrch']")).sendKeys(sh.getRow(1).getCell(10).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='theForm']/div/div[2]/input[2]")).click();
Thread.sleep(5000);
driver.switchTo().frame("resultsFrame");
driver.findElement(By.linkText(sh.getRow(1).getCell(10).getStringCellValue())).click();
driver.switchTo().window(mainWindow);
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:acctAdd:rptAddFields:7:actFields_lkwgt']/img")).click();
Thread.sleep(5000);
Set<String> winhandle = driver.getWindowHandles();
for(String str : winhandle)
{
if(!str.equalsIgnoreCase(mainWindow))
{
driver.switchTo().window(str);
break;
}
}
try
{
driver.switchTo().frame("searchFrame");
driver.findElement(By.xpath(".//*[#id='lksrch']")).sendKeys(sh.getRow(1).getCell(11).getStringCellValue());
driver.findElement(By.xpath(".//*[#id='theForm']/div/div[2]/input[2]")).click();
Thread.sleep(5000);
driver.switchTo().frame("resultsFrame");
driver.findElement(By.linkText(sh.getRow(1).getCell(11).getStringCellValue())).click();
driver.switchTo().window(mainWindow);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println();
driver.close();
driver.switchTo().window(mainWindow);
System.out.println("State/Region not Found");
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println();
driver.close();
driver.switchTo().window(mainWindow);
}
driver.findElement(By.xpath(".//*[#id='pg:acc:pb:j_id34:save']")).click();
Before switching to resultsFrame try to switch to defaultContent or your main frame and then switch to resultsFrame. The thing is webdriver searches the frame in current context. So under searchFrame it will never find the resultsFrame (As both might be under main frame).
Hope this helps.

Categories