9

I am not being able to open a new tab in chrome. My requirement is to open a new tab do some operation then close this new tab and come back to old tab. The below python code worked in Firefox but not working in Chrome. Could anyone please help me?

ActionChains(driver).key_down(Keys.CONTROL,body).send_keys('t').key_up(Keys.CONTROL).perform()
2
  • I have a similar problem. Seems that ChromeWebDriver doesn't support keys combinations Commented Jul 22, 2015 at 9:49
  • This is working with Firefox . my requirement is to open a new tab not by clicking on any link on the 1st tab Commented Jul 22, 2015 at 10:00

2 Answers 2

9

Guess this will be helpful:

from selenium import webdriver
driver = webdriver.Chrome()
driver.execute_script("window.open('','_blank');")

This piece of code should start new Chrome browser session and open blank page in new tab

Use driver.execute_script("window.open('URL');") to open new tab with required URL

Sign up to request clarification or add additional context in comments.

Comments

7

I failed to open new tab with required URL by driver.execute_script("window.open('URL');").

Therefore I changed my mind.

Any link will start on the new tab if we consider switching the current window to the new one. And I will open the new tab by driver.get(URL). The only method I need to use is driver.switch_to_window(driver.window_handles[1]).

We simply switch the window to the main window, when we close the new tab:driver.switch_to_window(driver.window_handles[0]) or driver.switch_to_window(main_window)

By the way, it will raise an error if we don't switch to the main window after closing the new tab.

from selenium import webdriver


driver = webdriver.Chrome()
driver.get("http://www.google.com/")

# save main_window
main_window = driver.current_window_handle

# obtain url of gmail on the home page of Google
addr = driver.find_element_by_xpath('//*[@id="gbw"]/div/div/div[1]/div[1]/a').get_attribute("href")

# open new blank tab
driver.execute_script("window.open();")

# switch to the new window which is second in window_handles array
driver.switch_to_window(driver.window_handles[1])

# open successfully and close
driver.get(addr)
driver.close()

# back to the main window
driver.switch_to_window(main_window)
driver.get(addr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.