0

I want Selenium to check if a window is open in Chrome browser or not, if yes, then open a new tab to the existing window Else, open a new window.

Currently I am using:

from selenium import webdriver
driver = webdriver.Chrome(chromedriver)
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') 

But this does not open a new tab in an existing open window. Kindly help.

user2458552
  • 419
  • 2
  • 5
  • 17
  • Does this answer your question? [selenium new tab in chrome browser by python webdriver](https://stackoverflow.com/questions/31559365/selenium-new-tab-in-chrome-browser-by-python-webdriver) – Ramon Medeiros Feb 03 '20 at 09:32
  • Hi, no.. this opens a new tab, closes -I want to look for is there is already an existing window- if yes, then open a new tab. – user2458552 Feb 03 '20 at 09:35
  • This is unclear, `webdriver.Chrome(chromedriver)` will open a new window. – Guy Feb 03 '20 at 09:36
  • To check if there is open windows: https://selenium-python.readthedocs.io/navigating.html#moving-between-windows-and-frames – Ramon Medeiros Feb 03 '20 at 09:37
  • Look for `driver.window_handles` – Ramon Medeiros Feb 03 '20 at 09:37
  • Exactly, the code above opens a new window.. What i need is open a new tab on an existing window- just like how a human would have behaved. Window handles would let me switch - but still have to open a window in that session – user2458552 Feb 03 '20 at 09:54
  • @user2458552 Are you talking about connecting to a browser that was opened manually? – Guy Feb 03 '20 at 11:18
  • @guy yes exactly – user2458552 Feb 03 '20 at 11:36
  • @user2458552 There are some posts with instructions how to do that, like [this one](https://stackoverflow.com/questions/48880646/python-selenium-use-a-browser-that-is-already-open-and-logged-in-with-login-cre), but I never tried it myself so I have no idea if it's really possible. – Guy Feb 03 '20 at 11:39

1 Answers1

0

If I understood your problem correctly.You would like check if any window is open then you need to open another tab.

For that You need check len(driver.window_handles)>0 then proceed and then using java script executor to open the new tab.

url="https://stackoverflow.com/"
driver=webdriver.Chrome()
if len(driver.window_handles)>0:
    driver.get(url) #proceed with same tab
    driver.execute_script("window.open('{}');".format(url)) #proceed with new tab
KunduK
  • 32,888
  • 5
  • 17
  • 41