0

I have to try to click an element on a web page, and I want the link after the click should open in a new tab, here is the code snippet:

browser.find_element_by_xpath('//*[@id="container"]/main/div/sec[1]').click()

# Above code open the link but in the same tab.

I have tried the following code to open it in a new tab:

browser.find_element_by_xpath('//*[@id="container"]/main/div/sec[1]').send_keys(Keys.CONTROL + 't').click()

# But it's not working. 

How to open this in a new tab?

P.S.: This is not the link to open in a new tab, its the element to be opened on a new tab, so don't mark it as duplicate.

Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
Kallol
  • 2,089
  • 3
  • 18
  • 33
  • 1
    Possible duplicate of [Opening link in the new tab and switching between tabs (Selenium WebDriver + Python)](https://stackoverflow.com/questions/46425797/opening-link-in-the-new-tab-and-switching-between-tabs-selenium-webdriver-pyt) – hashcode55 Jul 19 '19 at 06:37
  • @hashcode55 please read the both questions before marking it as duplicate – Kallol Jul 19 '19 at 06:51
  • @KallolSamanta Can you update the question with the relevant HTML? – undetected Selenium Jul 19 '19 at 07:13
  • @KallolSamanta What do you mean by "opening an element in a new tab"? The only difference I see between the your question and duplicate question is you are trying to find the element by xpath. – hashcode55 Jul 19 '19 at 07:18
  • @KallolSamanta, check out my answer (second not accepted one): https://stackoverflow.com/questions/46425797/opening-link-in-the-new-tab-and-switching-between-tabs-selenium-webdriver-pyt – Ratmir Asanov Jul 19 '19 at 08:31

1 Answers1

0

This should work in Java (Hope you can write this logic in Python),

To open a link in new tab

WebElement ele = wd.findElement(By.xpath(xpath));
Actions link = new Actions(wd);   
link.keyDown(Keys.COMMAND).click(ele).keyUp(Keys.COMMAND).build().perform();
Thread.sleep(5000);

Switch to new tab,

Set<String> windows = wd.getWindowHandles();
wd.switchTo().window((String) windows.toArray()[1]);
Chirag S
  • 63
  • 3