0

I have tried all the methods in similar questions and only one of them worked which was to use javascript.

    driver.execute_script("window.open('')")
    #this works

    ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
    #this doesn't
    
    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
    #this doesn't work either

I'd like to get the second way to work, since it seems the most readable and sensible, am I doing something wrong in my code? Or is there any option I need to change in Selenium to enable opening tabs like this?

Edit: The 2nd and 3rd method don't produce any result at all. Not even an exception.

Nayan Gautam
  • 122
  • 1
  • 5

2 Answers2

0

Below code works for me for opening and closing tabs:

import time

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")
time.sleep(2)
# open new tab
driver.execute_script("window.open('');")

# switch to the new tab and open new URL there
driver.switch_to.window(driver.window_handles[1])
driver.get("http://www.python.org")
time.sleep(2)
chld = driver.window_handles[1]
driver.switch_to.window(chld)
driver.close()

The second way didn't work for me as well.

rok
  • 9,403
  • 17
  • 70
  • 126
0

import the selenium module

from selenium import webdriver

creates selenium object

driver = webdriver.Chrome()

gets the url needed for the driver object

url = "https://www.google.com/"

Open a new window

driver.execute_script("window.open('');")

Close the tab

driver.close()
tarik
  • 33
  • 7