Home > Back-end >  Selenium window closes instantly when "requests" module is imported
Selenium window closes instantly when "requests" module is imported

Time:02-10

I'm trying to use Selenium and Beautiful Soup together with Python but having a rather strange issue - Selenium window stays opened only if requests module is not imported, otherwise it stays opened for like 1 second and closes.
Important thing is that this only happens when I create the class in another file - when I create the class in the same file it stays opened normally. Below are the two versions of code - 1st one where window stays opened, 2nd one where window instantly closes:

1: WORKS

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

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")

2: CLOSES

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test import Watcher
import requests

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")

CodePudding user response:

I'm wondering if this has something to do with the Keep-Alive and Connection Pooling in urllib3, even though the requests module is not used in the program code.

When your program terminates, the HTTP connections are released and the browser window closes.

Add this and you'll see that the browser window stays open until the program has finished running. The program simply terminates perfectly normally with no errors.

from time import sleep
for _ in range(10):
    sleep(1)
  • Related