Python - Selenium autmation tab is getting closed automatically after execution

49 views Asked by At

I am new to python and trying to learn Selenium with python. But when i execute the code the tab opensup and getting closed automatically after loading the url.i never face this issue using selenium with java. Can anyone suggest me some solution

here's the code

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

ser_obj = Service("D:\\Python\\chromedriver-win64\\chromedriver.exe")
driver = webdriver.Chrome(service=ser_obj)
driver.get("https://gmail.com")
2

There are 2 answers

2
adebayo On

That's because your Python script closes after it's done executing your commands. You can add input("Press enter to quit") to stop this closing from happening.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

ser_obj = Service("D:\\Python\\chromedriver-win64\\chromedriver.exe")
driver = webdriver.Chrome(service=ser_obj)
driver.get("https://gmail.com")

# This line of code will stop the python interpreter from closing. 
# which in turn will stop your selenium browser from closing as well.
input("Press enter to close the interpreter.")

Please try this out and let me know if it helps at all.

0
Yaroslavm On

Don't quit from browser after the end of test execution can be achieved by adding detach to experimental options.

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options)

driver.get("https://gmail.com")

Another (not very good) approaches can be:

  • Running test in debug mode, add empty print() on the line you want to stop and add breakpoint (in IDE)
  • Adding time.sleep(1000) after the line where you expect script exection should be stopped