How can I reconnect to the browser opened by webdriver with selenium?How to keep chrome browser window open to be re-used after selenium script finishes on pythonI want to re-use the browser which is already opened in robot frameworkPython - Can Selenium webdriver be attached to an existing running session in a browserOpen same session in Selenium web driver pythonHow to open site with Symantec plugin using Selenium.ChromeDriver?Firefox: session cookies not kept when browser is under remote controlSplit window handles into new ChromeDriver instancesAccessing an existing whatsapp-web session from selenium webdriverSelenium Python - Transfer Cookies from Session to WebdriverCan we attach a selenium web-driver session to an already opened browser?How can I represent an 'Enum' in Python?How to take screenshot with Selenium WebDriverGet HTML Source of WebElement in Selenium WebDriver using PythonHow to run Selenium WebDriver test cases in Chrome?How to use already opened browser active session in webdriverOpen new tab in chrome using Selenium Facebook PHP WebdriverSelenium Webdriver Error - SessionNotCreatedErrorReuse existing Selenium session with Haskell and webdriverhow to detect selenium/webdriver browsing on my sitePython Selenium Remote Webdriver(Chrome Webdriver via Selenium Grid), created but does not open browser
When is it ok to add filler to a story?
What happens when your group is victim of a surprise attack but you can't be surprised?
What is the difference between and Embedding Layer and an Autoencoder?
Impossible darts scores
Why do textbooks often include the solutions to odd or even numbered problems but not both?
Is it damaging to turn off a small fridge for two days every week?
Could Sauron have read Tom Bombadil's mind if Tom had held the Palantir?
How to get cool night-vision without lame drawbacks?
Can White Castle?
Do flight schools typically have dress codes or expectations?
Smooth Julia set for quadratic polynomials
Should I hide continue button until tasks are completed?
Should I include salary information on my CV?
STM Microcontroller burns every time
Change the boot order with no option in UEFI settings
ては's role in this 「追いかけては来ないでしょう」
First-year PhD giving a talk among well-established researchers in the field
How can I get more energy without spending coins?
Is there a maximum distance from a planet that a moon can orbit?
What is the legal status of travelling with (unprescribed) methadone in your carry-on?
Can’t attend PhD conferences
Distance Matrix (plugin) - QGIS
Why do some games show lights shine through walls?
A player is constantly pestering me about rules, what do I do as a DM?
How can I reconnect to the browser opened by webdriver with selenium?
How to keep chrome browser window open to be re-used after selenium script finishes on pythonI want to re-use the browser which is already opened in robot frameworkPython - Can Selenium webdriver be attached to an existing running session in a browserOpen same session in Selenium web driver pythonHow to open site with Symantec plugin using Selenium.ChromeDriver?Firefox: session cookies not kept when browser is under remote controlSplit window handles into new ChromeDriver instancesAccessing an existing whatsapp-web session from selenium webdriverSelenium Python - Transfer Cookies from Session to WebdriverCan we attach a selenium web-driver session to an already opened browser?How can I represent an 'Enum' in Python?How to take screenshot with Selenium WebDriverGet HTML Source of WebElement in Selenium WebDriver using PythonHow to run Selenium WebDriver test cases in Chrome?How to use already opened browser active session in webdriverOpen new tab in chrome using Selenium Facebook PHP WebdriverSelenium Webdriver Error - SessionNotCreatedErrorReuse existing Selenium session with Haskell and webdriverhow to detect selenium/webdriver browsing on my sitePython Selenium Remote Webdriver(Chrome Webdriver via Selenium Grid), created but does not open browser
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
For some unknown reasons ,my browser open test pages of my remote server very slowly. So I am thinking if I can reconnect to the browser after quitting the script but don't execute webdriver.quit()
this will leave the browser opened. It is probably kind of HOOK or webdriver handle.
I have looked up the selenium API doc but didn't find any function.
I'm using Chrome 62,x64,windows 7,selenium 3.8.0.
I'll be very appreciated whether the question can be solved or not.
python-3.x selenium session selenium-webdriver webdriver
|
show 1 more comment
For some unknown reasons ,my browser open test pages of my remote server very slowly. So I am thinking if I can reconnect to the browser after quitting the script but don't execute webdriver.quit()
this will leave the browser opened. It is probably kind of HOOK or webdriver handle.
I have looked up the selenium API doc but didn't find any function.
I'm using Chrome 62,x64,windows 7,selenium 3.8.0.
I'll be very appreciated whether the question can be solved or not.
python-3.x selenium session selenium-webdriver webdriver
1
Where's your code?
– Alan
Dec 18 '17 at 4:30
Have you tried reusing the chrome existing user directory by using the option 'user-data-dir' instead of webdriver creating a new one each time. Instead of downloading chrome will use stuff from the cache.
– Grasshopper
Dec 18 '17 at 4:37
@Grasshopper What is this black magic? I used this Chromeoption.And it reduced plenty of loading time. I'll lookup for this .Thank you very much.
– imbaiye
Dec 18 '17 at 6:24
It is the cache helping load the page so fast
– imbaiye
Dec 18 '17 at 7:18
Possible duplicate of Can Selenium interact with an existing browser session?
– JeffC
May 8 '18 at 20:50
|
show 1 more comment
For some unknown reasons ,my browser open test pages of my remote server very slowly. So I am thinking if I can reconnect to the browser after quitting the script but don't execute webdriver.quit()
this will leave the browser opened. It is probably kind of HOOK or webdriver handle.
I have looked up the selenium API doc but didn't find any function.
I'm using Chrome 62,x64,windows 7,selenium 3.8.0.
I'll be very appreciated whether the question can be solved or not.
python-3.x selenium session selenium-webdriver webdriver
For some unknown reasons ,my browser open test pages of my remote server very slowly. So I am thinking if I can reconnect to the browser after quitting the script but don't execute webdriver.quit()
this will leave the browser opened. It is probably kind of HOOK or webdriver handle.
I have looked up the selenium API doc but didn't find any function.
I'm using Chrome 62,x64,windows 7,selenium 3.8.0.
I'll be very appreciated whether the question can be solved or not.
python-3.x selenium session selenium-webdriver webdriver
python-3.x selenium session selenium-webdriver webdriver
edited Apr 26 at 9:41
DebanjanB
53.4k14 gold badges55 silver badges102 bronze badges
53.4k14 gold badges55 silver badges102 bronze badges
asked Dec 18 '17 at 3:34
imbaiyeimbaiye
391 silver badge4 bronze badges
391 silver badge4 bronze badges
1
Where's your code?
– Alan
Dec 18 '17 at 4:30
Have you tried reusing the chrome existing user directory by using the option 'user-data-dir' instead of webdriver creating a new one each time. Instead of downloading chrome will use stuff from the cache.
– Grasshopper
Dec 18 '17 at 4:37
@Grasshopper What is this black magic? I used this Chromeoption.And it reduced plenty of loading time. I'll lookup for this .Thank you very much.
– imbaiye
Dec 18 '17 at 6:24
It is the cache helping load the page so fast
– imbaiye
Dec 18 '17 at 7:18
Possible duplicate of Can Selenium interact with an existing browser session?
– JeffC
May 8 '18 at 20:50
|
show 1 more comment
1
Where's your code?
– Alan
Dec 18 '17 at 4:30
Have you tried reusing the chrome existing user directory by using the option 'user-data-dir' instead of webdriver creating a new one each time. Instead of downloading chrome will use stuff from the cache.
– Grasshopper
Dec 18 '17 at 4:37
@Grasshopper What is this black magic? I used this Chromeoption.And it reduced plenty of loading time. I'll lookup for this .Thank you very much.
– imbaiye
Dec 18 '17 at 6:24
It is the cache helping load the page so fast
– imbaiye
Dec 18 '17 at 7:18
Possible duplicate of Can Selenium interact with an existing browser session?
– JeffC
May 8 '18 at 20:50
1
1
Where's your code?
– Alan
Dec 18 '17 at 4:30
Where's your code?
– Alan
Dec 18 '17 at 4:30
Have you tried reusing the chrome existing user directory by using the option 'user-data-dir' instead of webdriver creating a new one each time. Instead of downloading chrome will use stuff from the cache.
– Grasshopper
Dec 18 '17 at 4:37
Have you tried reusing the chrome existing user directory by using the option 'user-data-dir' instead of webdriver creating a new one each time. Instead of downloading chrome will use stuff from the cache.
– Grasshopper
Dec 18 '17 at 4:37
@Grasshopper What is this black magic? I used this Chromeoption.And it reduced plenty of loading time. I'll lookup for this .Thank you very much.
– imbaiye
Dec 18 '17 at 6:24
@Grasshopper What is this black magic? I used this Chromeoption.And it reduced plenty of loading time. I'll lookup for this .Thank you very much.
– imbaiye
Dec 18 '17 at 6:24
It is the cache helping load the page so fast
– imbaiye
Dec 18 '17 at 7:18
It is the cache helping load the page so fast
– imbaiye
Dec 18 '17 at 7:18
Possible duplicate of Can Selenium interact with an existing browser session?
– JeffC
May 8 '18 at 20:50
Possible duplicate of Can Selenium interact with an existing browser session?
– JeffC
May 8 '18 at 20:50
|
show 1 more comment
3 Answers
3
active
oldest
votes
No, you can't reconnect to the previous Web Browser
session after quiting the script. Even if you are able to extract the Session ID
, Cookies
and other session attributes from the previous Browsing Session
still you won't be able to pass those attributes as a HOOK to the WebDriver
.
A cleaner way would be to call webdriver.quit()
and then span a new Browsing Session
.
History :
Previously there had been some discussions and attempts to reconnect WebDriver
to an existing running browsing session. You can find the discussions in these QA :
Allow webdriver to attach to a running browser
[docs] webdriver.firefox.useExisting not implemented
1
You totally understand and solved my confusion. I'll do cleanup . Thank you very much.
– imbaiye
Dec 18 '17 at 6:18
add a comment |
Yes, that's actually quite easy to do.
A selenium <-> webdriver session is represented by a connection url and session_id, you just reconnect to an existing one.
Disclaimer - the approach is using selenium internal properties ("private", in a way), which may change in new releases; you'd better not use it for production code; it's better not to be used against remote SE (yours hub, or provider like BrowserStack/Sauce Labs), because of a caveat/resource drainage explained at the end.
When a webdriver instance is initiated, you need to get the before-mentioned properties; sample:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.com/')
# now Google is opened, the browser is fully functional; print the two properties
# command_executor._url (it's "private", not for a direct usage), and session_id
print(f'driver.command_executor._url: driver.command_executor._url')
print(f'driver.session_id: driver.session_id')
With those two properties now known, another instance can connect; the "trick" is to initiate a Remote
driver, and provide the _url
above - thus it will connect to that running selenium process:
driver2 = webdriver.Remote(command_executor=the_known_url)
# when the started selenium is a local one, the url is in the form 'http://127.0.0.1:62526'
When that is ran, you'll see a new browser window being opened.
That's because upon initiating the driver, the selenium library automatically starts a new session for it - and now you have 1 webdriver process with 2 sessions (browsers instances).
If you navigate to an url, you'll see it is executed on that new browser instance, not the one that's left from the previous start - which is not the desired behavior.
At this point, two things need to be done - a) close the current SE session ("the new one"), and b) switch this instance to the previous session:
if driver2.session_id != the_known_session_id: # this is pretty much guaranteed to be the case
driver2.close() # this closes the session's window - it is currently the only one, thus the session itself will be auto-killed, yet:
driver2.quit() # for remote connections (like ours), this deletes the session, but does not stop the SE server
# take the session that's already running
driver2.session_id = the_known_session_id
# do something with the now hijacked session:
driver.get('https://www.bing.com/')
And, that is it - you're now connected to the previous/already existing session, with all its properties (cookies, LocalStorage, etc).
By the way, you do not have to provide desired_capabilities
when initiating the new remote driver - those are stored and inherited from the existing session you took over.
Caveat - having a SE process running can lead to some resource drainage in the system.
Whenever one is started and then not closed - like in the first piece of the code - it will stay there until you manually kill it. By this I mean - in Windows for example - you'll see a "chromedriver.exe" process, that you have to terminate manually once you are done with it. It cannot be closed by a driver that has connected to it as to a remote selenium process.
The reason - whenever you initiate a local browser instance, and then call its quit()
method, it has 2 parts in it - the first one is to delete the session from the Selenium instance (what's done in the second code piece up there), and the other is to stop the local service (the chrome/geckodriver) - which generally works ok.
The thing is, for Remote sessions the second piece is missing - your local machine cannot control a remote process, that's the work of that remote's hub. So that 2nd part is literally a pass
python statement - a no-op.
If you start too many selenium services on a remote hub, and don't have a control over it - that'll lead to resource drainage from that server. Cloud providers like BrowserStack take measures against this - they are closing services with no activity for the last 60s, etc, yet - this is something you don't want to do.
And as for local SE services - just don't forget to occasionally clean up the OS from orphaned selenium drivers you forgot about :)
add a comment |
Without getting into why do you think that leaving an open browser windows will solve the problem of being slow, you don't really need a handle to do that. Just keep running the tests without closing the session or, in other words, without calling driver.quit()
as you have mentioned yourself. The question here though framework that comes with its own runner? Like Cucumber?
In any case, you must have some "setup" and "cleanup" code. So what you need to do is to ensure during the "cleanup" phase that the browser is back to its initial state. That means:
- Blank page is displayed
- Cookies are erased for the session
So in such case, the setup code will open the browser and navigate to this page for you, then you run all your tests and the cleanup part will close the window and the browser. This does not look like a good practice as you are adding possible issues from not having a clean session each time but can work as a workaround. Also not sure how the page will behave if you clear the cookies after teach test.
– Eugene S
Dec 18 '17 at 5:37
The function <code>webdriver.Chrome.get(url)</code> will wait until the page loads completely.This will take a lot of time to load the remote page. So I want to open and load the page once. I think the webdriver is still running background after I quit my script . So I want to find the handle for the webdriver and reconnect to the webdriver to reuse the opened page
– imbaiye
Dec 18 '17 at 5:39
You edited your comment after I posted a reply but have a look at it see if this helps.
– Eugene S
Dec 18 '17 at 5:41
I'm sorry about that .Stackoverflow sets a 5 mintues edit time.And almost every time I make it time out.
– imbaiye
Dec 18 '17 at 5:48
My poor English.It is my bad.
– imbaiye
Dec 18 '17 at 5:49
|
show 2 more comments
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47861813%2fhow-can-i-reconnect-to-the-browser-opened-by-webdriver-with-selenium%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
No, you can't reconnect to the previous Web Browser
session after quiting the script. Even if you are able to extract the Session ID
, Cookies
and other session attributes from the previous Browsing Session
still you won't be able to pass those attributes as a HOOK to the WebDriver
.
A cleaner way would be to call webdriver.quit()
and then span a new Browsing Session
.
History :
Previously there had been some discussions and attempts to reconnect WebDriver
to an existing running browsing session. You can find the discussions in these QA :
Allow webdriver to attach to a running browser
[docs] webdriver.firefox.useExisting not implemented
1
You totally understand and solved my confusion. I'll do cleanup . Thank you very much.
– imbaiye
Dec 18 '17 at 6:18
add a comment |
No, you can't reconnect to the previous Web Browser
session after quiting the script. Even if you are able to extract the Session ID
, Cookies
and other session attributes from the previous Browsing Session
still you won't be able to pass those attributes as a HOOK to the WebDriver
.
A cleaner way would be to call webdriver.quit()
and then span a new Browsing Session
.
History :
Previously there had been some discussions and attempts to reconnect WebDriver
to an existing running browsing session. You can find the discussions in these QA :
Allow webdriver to attach to a running browser
[docs] webdriver.firefox.useExisting not implemented
1
You totally understand and solved my confusion. I'll do cleanup . Thank you very much.
– imbaiye
Dec 18 '17 at 6:18
add a comment |
No, you can't reconnect to the previous Web Browser
session after quiting the script. Even if you are able to extract the Session ID
, Cookies
and other session attributes from the previous Browsing Session
still you won't be able to pass those attributes as a HOOK to the WebDriver
.
A cleaner way would be to call webdriver.quit()
and then span a new Browsing Session
.
History :
Previously there had been some discussions and attempts to reconnect WebDriver
to an existing running browsing session. You can find the discussions in these QA :
Allow webdriver to attach to a running browser
[docs] webdriver.firefox.useExisting not implemented
No, you can't reconnect to the previous Web Browser
session after quiting the script. Even if you are able to extract the Session ID
, Cookies
and other session attributes from the previous Browsing Session
still you won't be able to pass those attributes as a HOOK to the WebDriver
.
A cleaner way would be to call webdriver.quit()
and then span a new Browsing Session
.
History :
Previously there had been some discussions and attempts to reconnect WebDriver
to an existing running browsing session. You can find the discussions in these QA :
Allow webdriver to attach to a running browser
[docs] webdriver.firefox.useExisting not implemented
edited Jan 20 '18 at 8:00
answered Dec 18 '17 at 6:00
DebanjanBDebanjanB
53.4k14 gold badges55 silver badges102 bronze badges
53.4k14 gold badges55 silver badges102 bronze badges
1
You totally understand and solved my confusion. I'll do cleanup . Thank you very much.
– imbaiye
Dec 18 '17 at 6:18
add a comment |
1
You totally understand and solved my confusion. I'll do cleanup . Thank you very much.
– imbaiye
Dec 18 '17 at 6:18
1
1
You totally understand and solved my confusion. I'll do cleanup . Thank you very much.
– imbaiye
Dec 18 '17 at 6:18
You totally understand and solved my confusion. I'll do cleanup . Thank you very much.
– imbaiye
Dec 18 '17 at 6:18
add a comment |
Yes, that's actually quite easy to do.
A selenium <-> webdriver session is represented by a connection url and session_id, you just reconnect to an existing one.
Disclaimer - the approach is using selenium internal properties ("private", in a way), which may change in new releases; you'd better not use it for production code; it's better not to be used against remote SE (yours hub, or provider like BrowserStack/Sauce Labs), because of a caveat/resource drainage explained at the end.
When a webdriver instance is initiated, you need to get the before-mentioned properties; sample:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.com/')
# now Google is opened, the browser is fully functional; print the two properties
# command_executor._url (it's "private", not for a direct usage), and session_id
print(f'driver.command_executor._url: driver.command_executor._url')
print(f'driver.session_id: driver.session_id')
With those two properties now known, another instance can connect; the "trick" is to initiate a Remote
driver, and provide the _url
above - thus it will connect to that running selenium process:
driver2 = webdriver.Remote(command_executor=the_known_url)
# when the started selenium is a local one, the url is in the form 'http://127.0.0.1:62526'
When that is ran, you'll see a new browser window being opened.
That's because upon initiating the driver, the selenium library automatically starts a new session for it - and now you have 1 webdriver process with 2 sessions (browsers instances).
If you navigate to an url, you'll see it is executed on that new browser instance, not the one that's left from the previous start - which is not the desired behavior.
At this point, two things need to be done - a) close the current SE session ("the new one"), and b) switch this instance to the previous session:
if driver2.session_id != the_known_session_id: # this is pretty much guaranteed to be the case
driver2.close() # this closes the session's window - it is currently the only one, thus the session itself will be auto-killed, yet:
driver2.quit() # for remote connections (like ours), this deletes the session, but does not stop the SE server
# take the session that's already running
driver2.session_id = the_known_session_id
# do something with the now hijacked session:
driver.get('https://www.bing.com/')
And, that is it - you're now connected to the previous/already existing session, with all its properties (cookies, LocalStorage, etc).
By the way, you do not have to provide desired_capabilities
when initiating the new remote driver - those are stored and inherited from the existing session you took over.
Caveat - having a SE process running can lead to some resource drainage in the system.
Whenever one is started and then not closed - like in the first piece of the code - it will stay there until you manually kill it. By this I mean - in Windows for example - you'll see a "chromedriver.exe" process, that you have to terminate manually once you are done with it. It cannot be closed by a driver that has connected to it as to a remote selenium process.
The reason - whenever you initiate a local browser instance, and then call its quit()
method, it has 2 parts in it - the first one is to delete the session from the Selenium instance (what's done in the second code piece up there), and the other is to stop the local service (the chrome/geckodriver) - which generally works ok.
The thing is, for Remote sessions the second piece is missing - your local machine cannot control a remote process, that's the work of that remote's hub. So that 2nd part is literally a pass
python statement - a no-op.
If you start too many selenium services on a remote hub, and don't have a control over it - that'll lead to resource drainage from that server. Cloud providers like BrowserStack take measures against this - they are closing services with no activity for the last 60s, etc, yet - this is something you don't want to do.
And as for local SE services - just don't forget to occasionally clean up the OS from orphaned selenium drivers you forgot about :)
add a comment |
Yes, that's actually quite easy to do.
A selenium <-> webdriver session is represented by a connection url and session_id, you just reconnect to an existing one.
Disclaimer - the approach is using selenium internal properties ("private", in a way), which may change in new releases; you'd better not use it for production code; it's better not to be used against remote SE (yours hub, or provider like BrowserStack/Sauce Labs), because of a caveat/resource drainage explained at the end.
When a webdriver instance is initiated, you need to get the before-mentioned properties; sample:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.com/')
# now Google is opened, the browser is fully functional; print the two properties
# command_executor._url (it's "private", not for a direct usage), and session_id
print(f'driver.command_executor._url: driver.command_executor._url')
print(f'driver.session_id: driver.session_id')
With those two properties now known, another instance can connect; the "trick" is to initiate a Remote
driver, and provide the _url
above - thus it will connect to that running selenium process:
driver2 = webdriver.Remote(command_executor=the_known_url)
# when the started selenium is a local one, the url is in the form 'http://127.0.0.1:62526'
When that is ran, you'll see a new browser window being opened.
That's because upon initiating the driver, the selenium library automatically starts a new session for it - and now you have 1 webdriver process with 2 sessions (browsers instances).
If you navigate to an url, you'll see it is executed on that new browser instance, not the one that's left from the previous start - which is not the desired behavior.
At this point, two things need to be done - a) close the current SE session ("the new one"), and b) switch this instance to the previous session:
if driver2.session_id != the_known_session_id: # this is pretty much guaranteed to be the case
driver2.close() # this closes the session's window - it is currently the only one, thus the session itself will be auto-killed, yet:
driver2.quit() # for remote connections (like ours), this deletes the session, but does not stop the SE server
# take the session that's already running
driver2.session_id = the_known_session_id
# do something with the now hijacked session:
driver.get('https://www.bing.com/')
And, that is it - you're now connected to the previous/already existing session, with all its properties (cookies, LocalStorage, etc).
By the way, you do not have to provide desired_capabilities
when initiating the new remote driver - those are stored and inherited from the existing session you took over.
Caveat - having a SE process running can lead to some resource drainage in the system.
Whenever one is started and then not closed - like in the first piece of the code - it will stay there until you manually kill it. By this I mean - in Windows for example - you'll see a "chromedriver.exe" process, that you have to terminate manually once you are done with it. It cannot be closed by a driver that has connected to it as to a remote selenium process.
The reason - whenever you initiate a local browser instance, and then call its quit()
method, it has 2 parts in it - the first one is to delete the session from the Selenium instance (what's done in the second code piece up there), and the other is to stop the local service (the chrome/geckodriver) - which generally works ok.
The thing is, for Remote sessions the second piece is missing - your local machine cannot control a remote process, that's the work of that remote's hub. So that 2nd part is literally a pass
python statement - a no-op.
If you start too many selenium services on a remote hub, and don't have a control over it - that'll lead to resource drainage from that server. Cloud providers like BrowserStack take measures against this - they are closing services with no activity for the last 60s, etc, yet - this is something you don't want to do.
And as for local SE services - just don't forget to occasionally clean up the OS from orphaned selenium drivers you forgot about :)
add a comment |
Yes, that's actually quite easy to do.
A selenium <-> webdriver session is represented by a connection url and session_id, you just reconnect to an existing one.
Disclaimer - the approach is using selenium internal properties ("private", in a way), which may change in new releases; you'd better not use it for production code; it's better not to be used against remote SE (yours hub, or provider like BrowserStack/Sauce Labs), because of a caveat/resource drainage explained at the end.
When a webdriver instance is initiated, you need to get the before-mentioned properties; sample:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.com/')
# now Google is opened, the browser is fully functional; print the two properties
# command_executor._url (it's "private", not for a direct usage), and session_id
print(f'driver.command_executor._url: driver.command_executor._url')
print(f'driver.session_id: driver.session_id')
With those two properties now known, another instance can connect; the "trick" is to initiate a Remote
driver, and provide the _url
above - thus it will connect to that running selenium process:
driver2 = webdriver.Remote(command_executor=the_known_url)
# when the started selenium is a local one, the url is in the form 'http://127.0.0.1:62526'
When that is ran, you'll see a new browser window being opened.
That's because upon initiating the driver, the selenium library automatically starts a new session for it - and now you have 1 webdriver process with 2 sessions (browsers instances).
If you navigate to an url, you'll see it is executed on that new browser instance, not the one that's left from the previous start - which is not the desired behavior.
At this point, two things need to be done - a) close the current SE session ("the new one"), and b) switch this instance to the previous session:
if driver2.session_id != the_known_session_id: # this is pretty much guaranteed to be the case
driver2.close() # this closes the session's window - it is currently the only one, thus the session itself will be auto-killed, yet:
driver2.quit() # for remote connections (like ours), this deletes the session, but does not stop the SE server
# take the session that's already running
driver2.session_id = the_known_session_id
# do something with the now hijacked session:
driver.get('https://www.bing.com/')
And, that is it - you're now connected to the previous/already existing session, with all its properties (cookies, LocalStorage, etc).
By the way, you do not have to provide desired_capabilities
when initiating the new remote driver - those are stored and inherited from the existing session you took over.
Caveat - having a SE process running can lead to some resource drainage in the system.
Whenever one is started and then not closed - like in the first piece of the code - it will stay there until you manually kill it. By this I mean - in Windows for example - you'll see a "chromedriver.exe" process, that you have to terminate manually once you are done with it. It cannot be closed by a driver that has connected to it as to a remote selenium process.
The reason - whenever you initiate a local browser instance, and then call its quit()
method, it has 2 parts in it - the first one is to delete the session from the Selenium instance (what's done in the second code piece up there), and the other is to stop the local service (the chrome/geckodriver) - which generally works ok.
The thing is, for Remote sessions the second piece is missing - your local machine cannot control a remote process, that's the work of that remote's hub. So that 2nd part is literally a pass
python statement - a no-op.
If you start too many selenium services on a remote hub, and don't have a control over it - that'll lead to resource drainage from that server. Cloud providers like BrowserStack take measures against this - they are closing services with no activity for the last 60s, etc, yet - this is something you don't want to do.
And as for local SE services - just don't forget to occasionally clean up the OS from orphaned selenium drivers you forgot about :)
Yes, that's actually quite easy to do.
A selenium <-> webdriver session is represented by a connection url and session_id, you just reconnect to an existing one.
Disclaimer - the approach is using selenium internal properties ("private", in a way), which may change in new releases; you'd better not use it for production code; it's better not to be used against remote SE (yours hub, or provider like BrowserStack/Sauce Labs), because of a caveat/resource drainage explained at the end.
When a webdriver instance is initiated, you need to get the before-mentioned properties; sample:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.google.com/')
# now Google is opened, the browser is fully functional; print the two properties
# command_executor._url (it's "private", not for a direct usage), and session_id
print(f'driver.command_executor._url: driver.command_executor._url')
print(f'driver.session_id: driver.session_id')
With those two properties now known, another instance can connect; the "trick" is to initiate a Remote
driver, and provide the _url
above - thus it will connect to that running selenium process:
driver2 = webdriver.Remote(command_executor=the_known_url)
# when the started selenium is a local one, the url is in the form 'http://127.0.0.1:62526'
When that is ran, you'll see a new browser window being opened.
That's because upon initiating the driver, the selenium library automatically starts a new session for it - and now you have 1 webdriver process with 2 sessions (browsers instances).
If you navigate to an url, you'll see it is executed on that new browser instance, not the one that's left from the previous start - which is not the desired behavior.
At this point, two things need to be done - a) close the current SE session ("the new one"), and b) switch this instance to the previous session:
if driver2.session_id != the_known_session_id: # this is pretty much guaranteed to be the case
driver2.close() # this closes the session's window - it is currently the only one, thus the session itself will be auto-killed, yet:
driver2.quit() # for remote connections (like ours), this deletes the session, but does not stop the SE server
# take the session that's already running
driver2.session_id = the_known_session_id
# do something with the now hijacked session:
driver.get('https://www.bing.com/')
And, that is it - you're now connected to the previous/already existing session, with all its properties (cookies, LocalStorage, etc).
By the way, you do not have to provide desired_capabilities
when initiating the new remote driver - those are stored and inherited from the existing session you took over.
Caveat - having a SE process running can lead to some resource drainage in the system.
Whenever one is started and then not closed - like in the first piece of the code - it will stay there until you manually kill it. By this I mean - in Windows for example - you'll see a "chromedriver.exe" process, that you have to terminate manually once you are done with it. It cannot be closed by a driver that has connected to it as to a remote selenium process.
The reason - whenever you initiate a local browser instance, and then call its quit()
method, it has 2 parts in it - the first one is to delete the session from the Selenium instance (what's done in the second code piece up there), and the other is to stop the local service (the chrome/geckodriver) - which generally works ok.
The thing is, for Remote sessions the second piece is missing - your local machine cannot control a remote process, that's the work of that remote's hub. So that 2nd part is literally a pass
python statement - a no-op.
If you start too many selenium services on a remote hub, and don't have a control over it - that'll lead to resource drainage from that server. Cloud providers like BrowserStack take measures against this - they are closing services with no activity for the last 60s, etc, yet - this is something you don't want to do.
And as for local SE services - just don't forget to occasionally clean up the OS from orphaned selenium drivers you forgot about :)
edited Jan 17 at 5:51
answered Aug 24 '18 at 11:12
Todor MinakovTodor Minakov
8,7211 gold badge29 silver badges39 bronze badges
8,7211 gold badge29 silver badges39 bronze badges
add a comment |
add a comment |
Without getting into why do you think that leaving an open browser windows will solve the problem of being slow, you don't really need a handle to do that. Just keep running the tests without closing the session or, in other words, without calling driver.quit()
as you have mentioned yourself. The question here though framework that comes with its own runner? Like Cucumber?
In any case, you must have some "setup" and "cleanup" code. So what you need to do is to ensure during the "cleanup" phase that the browser is back to its initial state. That means:
- Blank page is displayed
- Cookies are erased for the session
So in such case, the setup code will open the browser and navigate to this page for you, then you run all your tests and the cleanup part will close the window and the browser. This does not look like a good practice as you are adding possible issues from not having a clean session each time but can work as a workaround. Also not sure how the page will behave if you clear the cookies after teach test.
– Eugene S
Dec 18 '17 at 5:37
The function <code>webdriver.Chrome.get(url)</code> will wait until the page loads completely.This will take a lot of time to load the remote page. So I want to open and load the page once. I think the webdriver is still running background after I quit my script . So I want to find the handle for the webdriver and reconnect to the webdriver to reuse the opened page
– imbaiye
Dec 18 '17 at 5:39
You edited your comment after I posted a reply but have a look at it see if this helps.
– Eugene S
Dec 18 '17 at 5:41
I'm sorry about that .Stackoverflow sets a 5 mintues edit time.And almost every time I make it time out.
– imbaiye
Dec 18 '17 at 5:48
My poor English.It is my bad.
– imbaiye
Dec 18 '17 at 5:49
|
show 2 more comments
Without getting into why do you think that leaving an open browser windows will solve the problem of being slow, you don't really need a handle to do that. Just keep running the tests without closing the session or, in other words, without calling driver.quit()
as you have mentioned yourself. The question here though framework that comes with its own runner? Like Cucumber?
In any case, you must have some "setup" and "cleanup" code. So what you need to do is to ensure during the "cleanup" phase that the browser is back to its initial state. That means:
- Blank page is displayed
- Cookies are erased for the session
So in such case, the setup code will open the browser and navigate to this page for you, then you run all your tests and the cleanup part will close the window and the browser. This does not look like a good practice as you are adding possible issues from not having a clean session each time but can work as a workaround. Also not sure how the page will behave if you clear the cookies after teach test.
– Eugene S
Dec 18 '17 at 5:37
The function <code>webdriver.Chrome.get(url)</code> will wait until the page loads completely.This will take a lot of time to load the remote page. So I want to open and load the page once. I think the webdriver is still running background after I quit my script . So I want to find the handle for the webdriver and reconnect to the webdriver to reuse the opened page
– imbaiye
Dec 18 '17 at 5:39
You edited your comment after I posted a reply but have a look at it see if this helps.
– Eugene S
Dec 18 '17 at 5:41
I'm sorry about that .Stackoverflow sets a 5 mintues edit time.And almost every time I make it time out.
– imbaiye
Dec 18 '17 at 5:48
My poor English.It is my bad.
– imbaiye
Dec 18 '17 at 5:49
|
show 2 more comments
Without getting into why do you think that leaving an open browser windows will solve the problem of being slow, you don't really need a handle to do that. Just keep running the tests without closing the session or, in other words, without calling driver.quit()
as you have mentioned yourself. The question here though framework that comes with its own runner? Like Cucumber?
In any case, you must have some "setup" and "cleanup" code. So what you need to do is to ensure during the "cleanup" phase that the browser is back to its initial state. That means:
- Blank page is displayed
- Cookies are erased for the session
Without getting into why do you think that leaving an open browser windows will solve the problem of being slow, you don't really need a handle to do that. Just keep running the tests without closing the session or, in other words, without calling driver.quit()
as you have mentioned yourself. The question here though framework that comes with its own runner? Like Cucumber?
In any case, you must have some "setup" and "cleanup" code. So what you need to do is to ensure during the "cleanup" phase that the browser is back to its initial state. That means:
- Blank page is displayed
- Cookies are erased for the session
answered Dec 18 '17 at 4:56
Eugene SEugene S
4,8374 gold badges43 silver badges70 bronze badges
4,8374 gold badges43 silver badges70 bronze badges
So in such case, the setup code will open the browser and navigate to this page for you, then you run all your tests and the cleanup part will close the window and the browser. This does not look like a good practice as you are adding possible issues from not having a clean session each time but can work as a workaround. Also not sure how the page will behave if you clear the cookies after teach test.
– Eugene S
Dec 18 '17 at 5:37
The function <code>webdriver.Chrome.get(url)</code> will wait until the page loads completely.This will take a lot of time to load the remote page. So I want to open and load the page once. I think the webdriver is still running background after I quit my script . So I want to find the handle for the webdriver and reconnect to the webdriver to reuse the opened page
– imbaiye
Dec 18 '17 at 5:39
You edited your comment after I posted a reply but have a look at it see if this helps.
– Eugene S
Dec 18 '17 at 5:41
I'm sorry about that .Stackoverflow sets a 5 mintues edit time.And almost every time I make it time out.
– imbaiye
Dec 18 '17 at 5:48
My poor English.It is my bad.
– imbaiye
Dec 18 '17 at 5:49
|
show 2 more comments
So in such case, the setup code will open the browser and navigate to this page for you, then you run all your tests and the cleanup part will close the window and the browser. This does not look like a good practice as you are adding possible issues from not having a clean session each time but can work as a workaround. Also not sure how the page will behave if you clear the cookies after teach test.
– Eugene S
Dec 18 '17 at 5:37
The function <code>webdriver.Chrome.get(url)</code> will wait until the page loads completely.This will take a lot of time to load the remote page. So I want to open and load the page once. I think the webdriver is still running background after I quit my script . So I want to find the handle for the webdriver and reconnect to the webdriver to reuse the opened page
– imbaiye
Dec 18 '17 at 5:39
You edited your comment after I posted a reply but have a look at it see if this helps.
– Eugene S
Dec 18 '17 at 5:41
I'm sorry about that .Stackoverflow sets a 5 mintues edit time.And almost every time I make it time out.
– imbaiye
Dec 18 '17 at 5:48
My poor English.It is my bad.
– imbaiye
Dec 18 '17 at 5:49
So in such case, the setup code will open the browser and navigate to this page for you, then you run all your tests and the cleanup part will close the window and the browser. This does not look like a good practice as you are adding possible issues from not having a clean session each time but can work as a workaround. Also not sure how the page will behave if you clear the cookies after teach test.
– Eugene S
Dec 18 '17 at 5:37
So in such case, the setup code will open the browser and navigate to this page for you, then you run all your tests and the cleanup part will close the window and the browser. This does not look like a good practice as you are adding possible issues from not having a clean session each time but can work as a workaround. Also not sure how the page will behave if you clear the cookies after teach test.
– Eugene S
Dec 18 '17 at 5:37
The function <code>webdriver.Chrome.get(url)</code> will wait until the page loads completely.This will take a lot of time to load the remote page. So I want to open and load the page once. I think the webdriver is still running background after I quit my script . So I want to find the handle for the webdriver and reconnect to the webdriver to reuse the opened page
– imbaiye
Dec 18 '17 at 5:39
The function <code>webdriver.Chrome.get(url)</code> will wait until the page loads completely.This will take a lot of time to load the remote page. So I want to open and load the page once. I think the webdriver is still running background after I quit my script . So I want to find the handle for the webdriver and reconnect to the webdriver to reuse the opened page
– imbaiye
Dec 18 '17 at 5:39
You edited your comment after I posted a reply but have a look at it see if this helps.
– Eugene S
Dec 18 '17 at 5:41
You edited your comment after I posted a reply but have a look at it see if this helps.
– Eugene S
Dec 18 '17 at 5:41
I'm sorry about that .Stackoverflow sets a 5 mintues edit time.And almost every time I make it time out.
– imbaiye
Dec 18 '17 at 5:48
I'm sorry about that .Stackoverflow sets a 5 mintues edit time.And almost every time I make it time out.
– imbaiye
Dec 18 '17 at 5:48
My poor English.It is my bad.
– imbaiye
Dec 18 '17 at 5:49
My poor English.It is my bad.
– imbaiye
Dec 18 '17 at 5:49
|
show 2 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47861813%2fhow-can-i-reconnect-to-the-browser-opened-by-webdriver-with-selenium%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Where's your code?
– Alan
Dec 18 '17 at 4:30
Have you tried reusing the chrome existing user directory by using the option 'user-data-dir' instead of webdriver creating a new one each time. Instead of downloading chrome will use stuff from the cache.
– Grasshopper
Dec 18 '17 at 4:37
@Grasshopper What is this black magic? I used this Chromeoption.And it reduced plenty of loading time. I'll lookup for this .Thank you very much.
– imbaiye
Dec 18 '17 at 6:24
It is the cache helping load the page so fast
– imbaiye
Dec 18 '17 at 7:18
Possible duplicate of Can Selenium interact with an existing browser session?
– JeffC
May 8 '18 at 20:50