Lindau
Lindau

Reputation: 97

One session per tab with Selenium Web-driver?

I would like to create a new session for each tab I open and then control the sessions individually using Selenium python. Is this possible?

Upvotes: 5

Views: 2171

Answers (2)

Gravity API
Gravity API

Reputation: 879

First, no, you cannot. While tabs runs as a process, they are attached to the session ID which initially open the browser. This is how the protocol works https://www.w3.org/TR/webdriver/#new-session

They have, however, a unique ID which you can use to identify them by and switch between them.

driver.window_handles

will give you the list of open tabs. Each tab is fully isolated. You can now choose between

driver.switch_to_window("any open tab taken from windows handles list")
driver.do_something

driver.switch_to_window("any other tab from windows handles list")
driver.do_something_else_on_other_tab

# or (this option can let you run in parallel)
driver a = ChromeDriver()
driver b = ChromeDriver()

a.do_something
b.do_something

As suggested (and I personally do myself) open new session for each tab you want, that way you can parallel them and run much faster, all in all.

I am not sure the performance difference is that significant between multiple browsers or multiple tabs... they should use almost the same resources.

Upvotes: 0

koder613
koder613

Reputation: 1596

@reynoldsnp: Firefox has an official addon that does this, but I'm not sure if you can get selenium to interact with the addon. addons.mozilla.org/en-GB/firefox/addon/multi-account-containers If you figure out a way to do it, I would love to know how.

(I can't comment yet due to my reputation score, therefore quoted comment).

I don't know how to actually interact with the extension but if you have a known set of sites you would like to open:

Try this:

  1. Make a firefox profile for your use with selenium. Multiple profiles

    Windows 8/8.1/10: Press Win + R on your keyboard. Type firefox --new-instance --ProfileManager

  2. Open Firefox in that profile by selecting the new profile in the setup wizard. Install the extension in that profile.

selecting profile top open firefox with

  1. Set up the containers you would like in the extension, to, by default, open up with a specific site.

BY default open up sites with a container default opening sites Ensure that the checkbox is ticked.

  1. Start selenium with that profile like this:
from selenium import webdriver

profile = webdriver.FirefoxProfile('path/to/your/profile') # on windows found here: %APPDATA%/Mozilla/Firefox/Profiles

driver = webdriver.Firefox(firefox_profile=profile) 
  1. Navigate between tabs, effectively containers, using selenuium.

Upvotes: 2

Related Questions