Python Forum

Full Version: Need Help Opening A New Tab in Selenium
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
It seems simple enough, and I've tried a few different ways but none of them have worked so far. To Open a new tab in Chrome (which works the same way when done manually by hand in Selenium's Browser) you hold "CONTROL" and press "T".
These are the modules I'm working with:
>>> from selenium import webdriver
>>> driver = webdriver.Chrome()
>>> from selenium.webdriver.common.action_chains import ActionChains
>>> from selenium.webdriver.common.keys import Keys
Here is what I've tried so far with no results:
>>> ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
>>> # THIS DOES NOT GIVE AN ERROR, BUT IT ALSO DOES NOTHING
>>>
>>> menu = driver.find_element_by_tag_name('body')
>>> actions = ActionChains(driver)
>>> actions.move_to_element(menu).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
>>> # THIS GIVES NO ERROR ASWELL, BUT IT ALSO DOES NOTHING
>>> 
>>> driver.find_element_by_tag_name("body").send_keys(Keys.CONTROL + 't')
>>> # THIS GIVES NO ERROR AND DOES NOTHING. I SUSPECT IT PRESSES ONE KEY, RELEASES IT, THEN PRESSES THE OTHER. 
Neither of these ways give error, but neither works. Anyone have any ideas or advice, please leave a comment. Thank you.
this will open a new tab in chrome, set focus, close tab, then close the final tab
from selenium import webdriver
import time

driver = webdriver.Chrome('/home/metulburr/chromedriver')
driver.get('https://python-forum.io/Thread-Need-Help-Opening-A-New-Tab-in-Selenium')
# Open a new window
# This does not change focus to the new window for the driver.
driver.execute_script("window.open('');")
time.sleep(3)
# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("http://stackoverflow.com")
time.sleep(3)
# close the active tab
driver.close()
time.sleep(3)
# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("http://google.se")
time.sleep(3)
# Close the only tab, will also close the browser.
driver.close()
>>> driver.execute_script("window.open('');")
This actually did switch focus to the new window it created. Thank you again metulburr! :)

That one line was all I needed.

Edit: I realized what you meant by the driver itself switching tab focus. I created a list of window handles and told the driver to go to the last element in the list as this was the most recently opened tab. Like diz:
>>> driver.execute_script("window.open('');")
>>> Window_List = driver.window_handles
>>> driver.switch_to_window(Window_List[-1])