How to open a link in a new tab in a menu using Selenium in Java
Ashish Savaliya
I am trying to open a link in a new Tab in Selenium Java, but the first time only one link opens, but when opening the second link the For Loop is giving an error, can anyone help me with this.
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);
}
}
}
suburbs
You tried to open all sublinks in the product menu. But your sublink xpath points to the first sublink of all menus ( li[" + (i + 1) + "]/ul[@class='sublist']/li/a
) . So you need to modify the sublink xpath as below and try
SubLinks = driver.findElement(By.xpath("//ul[@class='top-menu']/li[1]/ul[@class='sublist']/li[" + (i + 1) + "]/a"));