Selenium send keys (text), selecting from dropdown and hit enter - java

I'm trying to trawl this website: http://www.jackson-stops.co.uk/
The data is not showing in the URL so I'm using a chromedriver.
My code is:
public static void main(String[] args) {
//setup chromedriver
File file = new File("C:\\Users\\USER\\Desktop\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
try {
driver.get("http://www.jackson-stops.co.uk/");
//begin the simulation
WebElement menu = driver.findElement(By.xpath("//*[#id=\"sliderLocation\"]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", menu);
menu.sendKeys("Knightsbridge");
Thread.sleep(4000);
Select menu2 = new Select(menu);
menu2.selectByVisibleText("Knightsbridge");
Thread.sleep(4000);
} catch (Exception exp) {
System.out.println("exception:" + exp);
//close and quit windows
driver.close();
driver.quit();
}
//close and quit windows
driver.close();
driver.quit();
}
The error that I get is:
exception:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"
How would I be able to select a location and hit enter because I tried inspecting the HTML and the options are dynamically loaded so not visible!

You are trying to select an element but it's not select list, it's a link, So all you have to do is to click that element, that's all
First of all pass value
driver.findElement(By.xpath("//*[#id='sliderLocation']")).sendKeys("Knightsbridge")
Once it's done, it populate the values, So You need to click one of option, So you can directly click the element like this(since this population is taking time, you need to use implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS))
And then write
driver.findElement(By.xpath("//a[text()='Knightsbridge, London']")).click()
Or if you want to choose the element which consist of Knightsbridge then write the following code and this will choose the first option which consist of Knightsbridge then write
driver.findElement(By.xpath("//a[contains(text(),'Knightsbridge']")).click()
You don't have to use sleep statement anywhere in your selenium code, selenium automatically waits after the click until everything settle down properly. The one exceptional case is, If your page got refreshed after placing the value in your text box(Not necessary for select_list), then you need to use the implicit wait, otherwise even implicit wait is not necessary.
The above code I converted from Ruby to Java, the original code which I used to check is from selenium Ruby binding, the code is below
#driver.find_element(:xpath, "//*[#id='sliderLocation']").send_keys "Knightsbridge"
#driver.manage.timeouts.implicit_wait = 10
#driver.find_element(:xpath, "//a[contains(text(),'Knightsbridge')]").click
#driver.find_element(:xpath, "//a[text()='Knightsbridge, London']").click

You can do as below:
String requiredCity = "London";
List<WebElement> menu2 = driver.findElements(By.xpath("//ul[#id='ui-id-3']/li"));
System.out.println("Total options: "+menu2.size());
for(int i=0;i<menu2.size();i++)
{
String CurrentOption = menu2.get(i).getText();
if(CurrentOption.contains(requiredCity)){
System.out.println("Found the city : "+CurrentOption);
menu2.get(i).click();
}
}

This is the full solution using Ranjeet's answer.
File file = new File("C:\\Users\\USER\\Desktop\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
try {
driver.get("http://www.jackson-stops.co.uk/");
//begin the simulation
WebElement menu = driver.findElement(By.xpath("//*[#id=\"sliderLocation\"]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", menu);
menu.sendKeys("London");
Thread.sleep(4000);
String requiredCity = "London";
List<WebElement> menu2 = driver.findElements(By.xpath("//ul[#id='ui-id-3']/li"));
System.out.println("Total options: " + menu2.size());
for (int i = 0; i < menu2.size(); i++) {
String CurrentOption = menu2.get(i).getText();
if (CurrentOption.contains(requiredCity)) {
System.out.println("Found the city : " + CurrentOption);
menu2.get(i).click();
Thread.sleep(6000);
menu.sendKeys(Keys.RETURN);
}
}
Thread.sleep(8000);
} catch (Exception exp) {
System.out.println("exception:" + exp);
//close and quit windows
driver.close();
driver.quit();
}
//close and quit
driver.close();
driver.quit();

WebElement selectMyElement = driver.findElement((By.xpath("//div/select/option[#value='Your value']")));
selectMyElement.sendKeys("Your value");
Actions keyDown = new Actions(myLauncher.getDriver());
keyDown.sendKeys(Keys.chord(Keys.DOWN, Keys.DOWN)).perform();

Related

How to wait till text value is fully loaded in selenium

I tried the following code in Selenium to get the row values.
public static void main(String[] args) throws InterruptedException {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www2.asx.com.au/");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
WebElement cookies = driver.findElementByXPath("//button[text()='Accept All Cookies']");
wait.until(ExpectedConditions.elementToBeClickable(cookies)).click();
} catch (Exception e) {
System.out.println("cookies pop up not found");
}
WebElement el = driver
.findElementByXPath("//*[#class='markit-home-top-five aem-GridColumn aem-GridColumn--default--12']");
wait.until(ExpectedConditions.visibilityOf(el));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", el);
List<WebElement> elements = driver.findElementsByXPath("//caption[text()='Gains']//ancestor::table//tr");
for (int i = 1; i <= elements.size(); i++) {
Thread.sleep(2000);
System.out.println(driver.findElementByXPath(
"//caption[text()='Gains']//ancestor::table//tr[" + i + "]//span[#class='value-with-arrow']")
.getText());
}
}
I faced two issues:
The 'Allow all cookies' button is not getting clicked and the pop up remains there. 'cookies pop up not found' is getting printed in the output.
The value of the tables are not getting printed without sleep. in the below output ,it is shown that the first text value is printed as -- as the value was still loading. How to provide till the value is fully loaded.
Thanks in advance!
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("element_id"), "The Text"));
use webdriver wait , you can use expected condition texttobepresent or element to be present
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#textToBePresentInElementLocated(org.openqa.selenium.By,java.lang.String)

How to open one by one link in new Tab from Menu using Selenium in Java

I am trying to open one by one link in new Tab in selenium Java, but only one link is opening the first time but For Loop goes wrong when open a second link, can anyone please help me to figure this out.
Here is my Code.
public class Link_Open_In_New_Tab {
public WebDriver driver;
#BeforeTest
public void OpenBrowser() {
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nopcommerce.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void OpenLink() throws InterruptedException {
List<WebElement> ProMenu;
WebElement SubLinks;
driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a")).click();
ProMenu = driver.findElements(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li/a"));
for (int i = 0; i < ProMenu.size(); i++) {
SubLinks = driver
.findElement(By.xpath("//ul[#class='top-menu']/li[" + (i + 1) + "]/ul[#class='sublist']/li/a"));
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).click(SubLinks).keyUp(Keys.CONTROL).build().perform();
Thread.sleep(2000);
String winHandleBefore = driver.getWindowHandle();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
Thread.sleep(2000);
driver.close();
Thread.sleep(2000);
driver.switchTo().window(winHandleBefore);
Thread.sleep(2000);
//driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a")).click();
//Thread.sleep(2000);
}
}
}
You were trying to open all the sublinks from the product menu. But your sublink xpath is pointing to the first sublink of all the menu (li[" + (i + 1) + "]/ul[#class='sublist']/li/a). So, you need to modify your sublink xpath as below and then try
SubLinks = driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li[" + (i + 1) + "]/a"));
You have to hover on Product, to get all the sub menus items. After then you can simulate keyboard strokes using Actions class which is available in Selenium and JAVA.
You can try this code :
public class Ashish {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user***\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nopcommerce.com/");
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a"))).build().perform();
List<WebElement> element = driver.findElements(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li/a"));
for(WebElement ele:element) {
action.keyDown(Keys.LEFT_CONTROL).moveToElement(ele).click().keyUp(Keys.LEFT_CONTROL).build().perform();
}
}
}
UPDATE 1 :
public class Ashish {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user***\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nopcommerce.com/");
WebDriverWait wait = new WebDriverWait(driver, 10);
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//ul[#class='top-menu']/li[1]/a"))).build().perform();
List<WebElement> element = driver.findElements(By.xpath("//ul[#class='top-menu']/li[1]/ul[#class='sublist']/li/a"));
System.out.println(element.size());
for(int i = 0 ; i<element.size() ; i++) {
action.keyDown(Keys.LEFT_CONTROL).moveToElement(wait.until(ExpectedConditions.elementToBeClickable(element.get(i)))).click().keyUp(Keys.LEFT_CONTROL).build().perform();
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
System.out.println(driver.getTitle());
driver.close();
driver.switchTo().window(tabs.get(0));
}
}
}
Console output :
9
nopCommerce - ASP.NET free shopping cart solution. What is nopCommerce?
nopCommerce - ASP.NET Open-source Ecommerce Shopping Cart Solution
nopCommerce - ASP.NET open source eCommerce solution. Feature list.
nopCommerce - Shopping Cart Demo & Shopping Cart Solution
nopCommerce - open source shopping cart. Showcase. Live Shops.
nopCommerce - open source shopping cart. Case Studies and Success Stories.
nopCommerce - ASP.NET open source shopping cart. Roadmap.
nopCommerce copyright removal key - nopCommerce
The nopCommerce Public License Version 3.0 ("NPL") - nopCommerce
If your intention is to test the links title to be working as expected or not then why need to you Crtl+click.
As per development, link here is to click but not ctrl+click, personally i am not willing to do this action.
Create variable say int i=1;
in loop like used, go for normal click and verify title. then increment i and go for browser back.

Java Selenium WebDriver unable to place first item into basket

Following is short program & in the following web site:
https://uk.webuy.com/search/index.php?stext=*&section=&catid=956
I am trying to click the first three product's "I want to buy this item" button &
view them in the VIEW BASKET at the right side of the page.
For some reason, I am able to see the second and third product only. For some reason, the first product never makes it to the basket, & it does not produce an error.
Only when I change the following line:
allButtons.get(0).click();
to:
allButtons.get(0).click();
allButtons.get(0).click();
allButtons.get(0).click();
I will see one occurrence of the first product in the basket.
What am I doing wrong? Is there something missing that is causing this problem?
Using Java 1.8
Selenium WebDrive Version #2.48
Mac OS Version #10.11.13
Thank you
public class ZWeBuy {
static WebDriver driver;
#Test
public void testProductPurchaseProcess() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://uk.webuy.com/search/index.php?stext=*&section=&catid=956");
closePopupIfPresent();
//xpath for all product names in this page
List<WebElement> allNames = driver.findElements(By.xpath("//div[#class='searchRecord']/div[2]/h1/a"));
List<WebElement> allButtons = driver.findElements(By.xpath("//div[#class='action']/div/a[2]/div/span"));
System.out.println("Total names = "+ allNames.size());
System.out.println("Total buttons = "+ allButtons.size());
System.out.println("I= " + 0 + " PRDCT: --- " +allNames.get(0).getText());
allButtons.get(0).click();
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("html/body/div[5]/div[1]/div[3]/div[5]/div[1]/div[1]/div[3]/div/a[2]/div/span")));
System.out.println("I= " + 1 + " PRDCT: --- " +allNames.get(1).getText());
allButtons.get(1).click();
System.out.println("I= " + 2 + " PRDCT: --- " +allNames.get(2).getText());
allButtons.get(2).click();
}
public static void closePopupIfPresent(){
Set<String> winIds = driver.getWindowHandles();
System.out.println("Total windows -> "+ winIds.size());
if(winIds.size() == 2){
Iterator<String> iter = winIds.iterator();
String mainWinID = iter.next();
String popupWinID = iter.next();
driver.switchTo().window(popupWinID);
driver.close();
driver.switchTo().window(mainWinID);
}
}
}
Your code isn't functional. Popup closing logic doesn't work, its actually not a separate window, its a dialog box within the same window. You should also consider simplifying your selectors. Alright enough said, here is working and tested code.
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://uk.webuy.com/search/index.php?stext=*&section=&catid=956");
WebElement element;
try {
element = driver.findElement(By.cssSelector(".deliver-component-wrapper>a>div"));
System.out.println("Closing pop up");
element.click();
} catch (NoSuchElementException e) {
System.out.println("Alright, no such dialog box, move on");
}
List<WebElement> buyButtons = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(
"span.listBuyButton_mx")));
Assert.assertTrue("Less than three buttons found", buyButtons.size() >= 3);
for (int i = 0; i < 3; i++) {
WebElement buyButton = buyButtons.get(i);
wait.until(ExpectedConditions.elementToBeClickable(buyButton)).click();
System.out.println("Clicked Buy Button " + (i + 1));
}
WebElement basketCount = wait
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#buyBasketRow>td.basketTableCell")));
System.out.println(basketCount.getText());
driver.quit();
It prints
Closing pop up
Clicked Buy Button 1
Clicked Buy Button 2
Clicked Buy Button 3
3 item/s
Your browser could not render that first button. you may put wait.until() method before each click event.
try this
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[5]/div[1]/div[3]/div[5]/div[1]/div[1]/div[3]/div/a[1]/div/span")));
allButtons.get(0).click();

How can I test a dropdown menu in Java from a generated selenium test case?

I am converting one of my Selenium test cases to Java and I am having a problem. The test involves checking links in drop down menus. My code is working sporadically on some of the links. Do I need to add this before each link test? I can make it a method if that is the case.
driver.get(baseUrl + "/");
try {
driver.findElement(By.cssSelector("a.dropdown-toggle")).click();
}
catch (Exception e) {
new SendMail("janet.frank#rodale.com",to_email,"CSS Selector","Error in cssSelector execution");
errorsFound = true;
}
Here is the method for the xpath:
private void executeXpath (String urlName, String value) {
String msg = "";
String xPath = "(//a[contains(text(),'" + urlName + "')])[" + value + "]";
try {
driver.findElement(By.xpath(xPath)).click();
checkUrl(urlName);
} catch (Exception e) {
msg = urlName + " test was not successful";
new SendMail("janet.frank#rodale.com",to_email,urlName,msg);
errorsFound = true;
}
// driver.navigate().back();
wait_fiveSeconds();
}
I have tried doing waits, executing the CSS dropdown method before each link but short of me staying hovered over the main header so that the dropdown stays visible does not work.
So I saw this code example posted, but what do I import so that I can create and Actions chain?
Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("//html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).build().perform();
I need to have my code execute the link and go to new pages but it does not seem to be doing that using the Actions API. Any help would be appreciated.

Switch tabs using Selenium WebDriver with Java

Using Selenium WebDriver with Java.
I am trying to automate a functionality where I have to open a new tab do some operations there and come back to previous tab (Parent).
I used switch handle but it's not working.
And one strange thing the two tabs are having same window handle due to which I am not able to switch between tabs.
However when I am trying with different Firefox windows it works, but for tab it's not working.
How can I switch tabs?
Or, how can I switch tabs without using window handle as window handle is same of both tabs in my case?
(I have observed that when you open different tabs in same window, window handle remains same)
psdbComponent.clickDocumentLink();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
driver.close();
driver.switchTo().window(tabs2.get(0));
This code perfectly worked for me. Try it out. You always need to switch your driver to new tab, before you want to do something on new tab.
This is a simple solution for opening a new tab, changing focus to it, closing the tab and return focus to the old/original tab:
#Test
public void testTabs() {
driver.get("https://business.twitter.com/start-advertising");
assertStartAdvertising();
// considering that there is only one tab opened in that point.
String oldTab = driver.getWindowHandle();
driver.findElement(By.linkText("Twitter Advertising Blog")).click();
ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
newTab.remove(oldTab);
// change focus to new tab
driver.switchTo().window(newTab.get(0));
assertAdvertisingBlog();
// Do what you want here, you are in the new tab
driver.close();
// change focus back to old tab
driver.switchTo().window(oldTab);
assertStartAdvertising();
// Do what you want here, you are in the old tab
}
private void assertStartAdvertising() {
assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
}
private void assertAdvertisingBlog() {
assertEquals("Twitter Advertising", driver.getTitle());
}
There is a difference how web driver handles different windows and how it handles different tabs.
Case 1:
In case there are multiple windows, then the following code can help:
//Get the current window handle
String windowHandle = driver.getWindowHandle();
//Get the list of window handles
ArrayList tabs = new ArrayList (driver.getWindowHandles());
System.out.println(tabs.size());
//Use the list of window handles to switch between windows
driver.switchTo().window(tabs.get(0));
//Switch back to original window
driver.switchTo().window(mainWindowHandle);
Case 2:
In case there are multiple tabs in the same window, then there is only one window handle. Hence switching between window handles keeps the control in the same tab. In this case using Ctrl + \t (Ctrl + Tab) to switch between tabs is more useful.
//Open a new tab using Ctrl + t
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Switch between tabs using Ctrl + \t
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
Detailed sample code can be found here:
http://design-interviews.blogspot.com/2014/11/switching-between-tabs-in-same-browser-window.html
Work around
Assumption : By Clicking something on your web page leads to open a new tab.
Use below logic to switch to second tab.
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();
In the same manner you can switch back to first tab again.
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD1).build().perform();
Since the driver.window_handles is not in order , a better solution is this.
first switch to the first tab using the shortcut Control + X to switch to the 'x' th tab in the browser window .
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "1");
# goes to 1st tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "4");
# goes to 4th tab if its exists or goes to last tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
WebElement e = driver.findElement(By
.xpath("html/body/header/div/div[1]/nav/a"));
e.sendKeys(selectLinkOpeninNewTab);//to open the link in a current page in to the browsers new tab
e.sendKeys(Keys.CONTROL + "\t");//to move focus to next tab in same browser
try {
Thread.sleep(8000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//to wait some time in that tab
e.sendKeys(Keys.CONTROL + "\t");//to switch the focus to old tab again
Hope it helps to you..
The first thing you need to do is opening a new tab and save it's handle name. It will be best to do it using javascript and not keys(ctrl+t) since keys aren't always available on automation servers. example:
public static String openNewTab(String url) {
executeJavaScript("window.parent = window.open('parent');");
ArrayList<String> tabs = new ArrayList<String>(bot.driver.getWindowHandles());
String handleName = tabs.get(1);
bot.driver.switchTo().window(handleName);
System.setProperty("current.window.handle", handleName);
bot.driver.get(url);
return handleName;
}
The second thing you need to do is switching between the tabs. Doing it by switch window handles only, will not always work since the tab you'll work on, won't always be in focus and Selenium will fail from time to time.
As I said, it's a bit problematic to use keys, and javascript doesn't really support switching tabs, so I used alerts to switch tabs and it worked like a charm:
public static void switchTab(int tabNumber, String handleName) {
driver.switchTo().window(handleName);
System.setProperty("current.window.handle", handleName);
if (tabNumber==1)
executeJavaScript("alert(\"alert\");");
else
executeJavaScript("parent.alert(\"alert\");");
bot.wait(1000);
driver.switchTo().alert().accept();
}
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL,Keys.SHIFT,Keys.TAB);
This method helps in switching between multiple windows. The restricting problem with this method is that it can only be used so many times until the required window is reached. Hope it helps.
With Selenium 2.53.1 using firefox 47.0.1 as the WebDriver in Java: no matter how many tabs I opened, "driver.getWindowHandles()" would only return one handle so it was impossible to switch between tabs.
Once I started using Chrome 51.0, I could get all handles. The following code show how to access multiple drivers and multiple tabs within each driver.
// INITIALIZE TWO DRIVERS (THESE REPRESENT SEPARATE CHROME WINDOWS)
driver1 = new ChromeDriver();
driver2 = new ChromeDriver();
// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
driver1.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
Thread.sleep(100);
// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs1 = new ArrayList<String> (driver1.getWindowHandles());
// REPEAT FOR THE SECOND DRIVER (SECOND CHROME BROWSER WINDOW)
// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
driver2.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
Thread.sleep(100);
// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs2 = new ArrayList<String> (driver1.getWindowHandles());
// NOW PERFORM DESIRED TASKS WITH FIRST BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
driver1.switchTo().window(tabs1.get(ii));
// LOGIC FOR THAT DRIVER'S CURRENT TAB
}
// PERFORM DESIRED TASKS WITH SECOND BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
drvier2.switchTo().window(tabs2.get(ii));
// LOGIC FOR THAT DRIVER'S CURRENT TAB
}
Hopefully that gives you a good idea of how to manipulate multiple tabs in multiple browser windows.
Simple Answer which worked for me:
for (String handle1 : driver1.getWindowHandles()) {
System.out.println(handle1);
driver1.switchTo().window(handle1);
}
Set<String> tabs = driver.getWindowHandles();
Iterator<String> it = tabs.iterator();
tab1 = it.next();
tab2 = it.next();
driver.switchTo().window(tab1);
driver.close();
driver.switchTo().window(tab2);
Try this. It should work
public void switchToNextTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void closeAndSwitchToNextTab() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
}
public void switchToPreviousTab() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void closeTabAndReturn() {
driver.close();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(0));
}
public void switchToPreviousTabAndClose() {
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
driver.close();
}
I had a problem recently, the link was opened in a new tab, but selenium focused still on the initial tab.
I'm using Chromedriver and the only way to focus on a tab was for me to use switch_to_window().
Here's the Python code:
driver.switch_to_window(driver.window_handles[-1])
So the tip is to find out the name of the window handle you need, they are stored as list in
driver.window_handles
Please see below:
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.irctc.co.in/");
String oldTab = driver.getWindowHandle();
//For opening window in New Tab
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("Hotels & Lounge")).sendKeys(selectLinkOpeninNewTab);
// Perform Ctrl + Tab to focus on new Tab window
new Actions(driver).sendKeys(Keys.chord(Keys.CONTROL, Keys.TAB)).perform();
// Switch driver control to focused tab window
driver.switchTo().window(oldTab);
driver.findElement(By.id("textfield")).sendKeys("bangalore");
Hope this is helpful!
It is A very simple process: assume you have two tabs so you need to first close the current tab by using client.window(callback) because the switch command "switches to the first available one". Then you can easily switch tab using client.switchTab.
A brief example of how to switch between tabs in a browser (in case with one window):
// open the first tab
driver.get("https://www.google.com");
Thread.sleep(2000);
// open the second tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.get("https://www.google.com");
Thread.sleep(2000);
// switch to the previous tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "" + Keys.SHIFT + "" + Keys.TAB);
Thread.sleep(2000);
I write Thread.sleep(2000) just to have a timeout to see switching between the tabs.
You can use CTRL+TAB for switching to the next tab and CTRL+SHIFT+TAB for switching to the previous tab.
This will work for the MacOS for Firefox and Chrome:
// opens the default browser tab with the first webpage
driver.get("the url 1");
thread.sleep(2000);
// opens the second tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND + "t");
driver.get("the url 2");
Thread.sleep(2000);
// comes back to the first tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND, Keys.SHIFT, "{");
To get parent window handles.
String parentHandle = driverObj.getWindowHandle();
public String switchTab(String parentHandle){
String currentHandle ="";
Set<String> win = ts.getDriver().getWindowHandles();
Iterator<String> it = win.iterator();
if(win.size() > 1){
while(it.hasNext()){
String handle = it.next();
if (!handle.equalsIgnoreCase(parentHandle)){
ts.getDriver().switchTo().window(handle);
currentHandle = handle;
}
}
}
else{
System.out.println("Unable to switch");
}
return currentHandle;
}
The flaw with the selected answer is that it unnecessarily assumes order in webDriver.getWindowHandles(). The getWindowHandles() method returns a Set, which does not guarantee order.
I used the following code to change tabs, which does not assume any ordering.
String currentTabHandle = driver.getWindowHandle();
String newTabHandle = driver.getWindowHandles()
.stream()
.filter(handle -> !handle.equals(currentTabHandle ))
.findFirst()
.get();
driver.switchTo().window(newTabHandle);
protected void switchTabsUsingPartOfUrl(String platform) {
String currentHandle = null;
try {
final Set<String> handles = driver.getWindowHandles();
if (handles.size() > 1) {
currentHandle = driver.getWindowHandle();
}
if (currentHandle != null) {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
break;
}
}
} else {
for (final String handle : handles) {
driver.switchTo().window(handle);
if (currentUrl().contains(platform)) {
break;
}
}
}
} catch (Exception e) {
System.out.println("Switching tabs failed");
}
}
Call this method and pass parameter a substring of url of the tab you want to switch to
public class TabBrowserDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println("Main Started");
System.setProperty("webdriver.gecko.driver", "driver//geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.irctc.co.in/eticketing/userSignUp.jsf");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[text()='Flights']")).click();
waitForLoad(driver);
Set<String> ids = driver.getWindowHandles();
Iterator<String> iterator = ids.iterator();
String parentID = iterator.next();
System.out.println("Parent WIn id " + parentID);
String childID = iterator.next();
System.out.println("child win id " + childID);
driver.switchTo().window(childID);
List<WebElement> hyperlinks = driver.findElements(By.xpath("//a"));
System.out.println("Total links in tabbed browser " + hyperlinks.size());
Thread.sleep(3000);
// driver.close();
driver.switchTo().window(parentID);
List<WebElement> hyperlinksOfParent = driver.findElements(By.xpath("//a"));
System.out.println("Total links " + hyperlinksOfParent.size());
}
public static void waitForLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
WebDriver driver = new FirefoxDriver();
driver.switchTo().window(driver.getWindowHandles().toArray()[numPage].toString());
numPage - int (0,1..)
String mainWindow = driver.getWindowHandle();
seleniumHelper.switchToChildWindow();
..
..//your assertion steps
seleniumHelper.switchToWindow(mainWindow);
with Java I used this for switching the selenium focus to the new tab.
//Before the action that redirect to the new tab:
String windHandleCurrent = driver.getWindowHandle();
// code that click in a btn/link in order to open a new tab goes here
// now to make selenium move to the new tab
ArrayList<String> windows = new ArrayList<String>(driver.getWindowHandles());
for(int i =0;i<windows.size();i++ ) {
String aWindow = windows.get(i);
if(aWindow != windHandleCurrent) {
driver.switchTo().window(aWindow);
}
}
// now you can code your AssertJUnit for the new tab.
Selenium 4 has new features:
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB);
// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW);
driver.getWindowHandles() is a Set.I converted it to array of objects by
Object[] a=driver.getWindowHandles().toArray;
Say you want to switch to 2nd tab then (after conversion) use
driver.switchTo().windows(a[1].toString());

Categories