简体   繁体   中英

python multiple instance of selenium webdriver

I have a question about selenium webdriver for python. I'm creating an instance of Chrome to login into a website, then I would like to create multiple instances of webdriver USING the same first instance (like a copy) or at least multiple instances which keep stored credentials that I used.

simple code :

options = webdriver.ChromeOptions()
options.binary_location = "path/to/chrome.exe"

browser1 = webdriver.Chrome(chrome_options=options)
browser1.get(login_url)

browser1.find_element_by_name('auth-email').send_keys('@gmail.com')
browser1.find_element_by_name('auth-password').send_keys('pass' + Keys.RETURN)

Example :

I logged into https://github.com/ with browser1. If I open a new instance browser2 and browser3 and I get url like https://github.com/pulls which needs to be logged to see contents, I have to RE-LOGIN again to see content.

Is there a way to copy credentials from browser1 to browser2 and browser3 ? Thanks in advance and sorry for my english,

Selenium does not offer a method to "clone" a new Selenium instance from an other one.

One thing you can do is to extract the authentication cookies from the first browser and pass them to the new browsers. For instance, to save the value of the sessionid cookie:

sessionid = driver.get_cookie("sessionid")["value"]

and set it:

driver.add_cookie({'name': 'sessionid',
                   'value': sessionid})

I use this kind of code to avoid having to login for each test in a large test suite. You must fetch a page from the web site first before you can set cookies for that site.

There's a caveat, however. This won't generally work if the cookie is marked HTTP-only. This is set by the web site. When a cookie is HTTP-only, it cannot be accessed by JavaScript code that run in web pages. A while back, I found that Selenium in fact was able to access HTTP-only cookies in FF and Chrome but not in IE. I do not know whether this inconsistent behavior has changed but for my tests I turned of the HTTP-only flag. (In production, it is turned on.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM