Switching windows or tabs is also possible from Python selenium code. The example below uses the selenium module and web driver.
This should work for all the supported web browsers including Chrome, Firefox, IE and all the others.
Related course:
switch to window
selenium switch to window
Before you start, install the selenium module, the Web Driver for your browser and the browser itself. The way this works is that the web driver controls the browser, and Python communicates with the web driver.
The selenium switch to window code shown below. It starts firefox, opens a webpage, then a new tab and window with different web sites.
1 | # -*- coding: utf-8 -*- |
First it opens the web browser this way:
1 | browser=webdriver.Firefox() |
Then it opens a new tab and switches to that tab.
1 | print(browser.window_handles) |
In the new tab it opens new url
1 | time.sleep(1) |
Then it switchse back to the first tab
1 | browser.switch_to_window(browser.window_handles[0]) |
If you are new to selenium, then I highly recommend this book.