Wednesday, October 17, 2018

Python - Open a new Tab instead of new Window with Selenium with Firefox in Python

Pretty crazy to work with multi-tab in Firefox with Selenium and here is some tips...
  1. locate webdriver_prefs.json under \\python_path\Lib\site-packages\selenium\
  2. set "browser.link.open_newwindow" from 2 to 3
  3. save before exit.
In program code, I did try using send_keys(Keys.CONTROL + 't') but it didn't succeed.
from selenium.webdriver.common.keys import Keys
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
You have to use javascript to call a new 'window'(tab) and then switch the current 'window'(tab) to newly created 'window'(tab)
driver.execute_script("window.open()")
driver.switch_to.window(driver.window_handles[-1])
After all the operation, you can close the newly created 'windows'(tab)
driver.close()
Remember, once you close the current 'window'(tab), you have to switch the 'window'(tab) back to first one(or another one) to access 'driver' or you will get an error saying the content has been dropped.
driver.switch_to.window(driver.window_handles[0])
A note for myself and for whom it may be interested in

No comments: