0

I needed to use same instance of selenium web driver across different python files. This is my base class.

class Automate(object):

    def __init__(self):
        self.options = webdriver.ChromeOptions()
        self.options.add_argument('--user-data-dir=\\profile path')
        self.driver = webdriver.Chrome(executable_path="\\driver path", options=self.options)

    def get(self, url):
        self.driver.get(url)

Now, when I try to instantiate an object for this class in two different files like temp.py and test.py,

In temp.py

import automate    
driver1 = Automate()
driver1.get("google.com")

In test.py

import automate
driver2 = Automate()
driver2.get("google.com")

The result is opening of two seperate chrome windows. I want these two files to use only one instance of the web driver. I tried searching for answers, someone said to use singleton classes (I don't know much about singleton class).

Can someone please give me an example on how to use the single driver instance across multiple python files.

What I want: I need 1st file to open the browser and 2nd file to send commands like get, find elements by xpath. Also, I want the 2nd file to be re runnable without opening a new browser window.

2
  • I think you'd need the sessionID of the first driver. Can you explain more about why are you trying to do this? Commented Nov 3, 2020 at 20:40
  • @pcalkins Thanks for your reply. My aim is using one file to open the browser and using another file to control the opened browser like get, find elements by xpath etc., for some reason I cant find a way. Please help me Commented Nov 4, 2020 at 6:37

2 Answers 2

1

The simpler solution that worked for me (at least so far). Python allows you to import hassle free - if you are going down directories/packages. I am using packages. I crated a simple driver file where I reference driver path. Then I imported that file in my package which is located 'one step up in directory.'

In the package where I want to re-use the driver, I call "from 'package.name' import 'driver'

Then I can use driver in my script.

Sign up to request clarification or add additional context in comments.

Comments

0

I found a solution to my problem by using chrome remote debugging. First of all, I checked whether chrome is running or not with this piece of code. I know this is little but anyways, it worked for me. I created few files singleton.py, admin_chrome.bat, chrome.bat

In admin_chrome.bat

@echo off
start "" Powershell -Command "& { Start-process \"chrome.bat\" -ArgumentList @(\"C:\\Windows\\System32\\drivers\\etc\\hosts\") -Verb RunAs } "

In chrome.bat,

@echo off
start "" chrome.exe --remote-debugging-port=9222 --user-data- 
dir="F:\Programs\Projects Folder\ChromeProfile\Default"
exit

In singleton.py

import asyncio
import psutil
import os

admin = r'admin_chrome.bat'
chrome_status = "temp.txt"


async def initialize():
    if not await chrome_status_checker():
        await chrome_status_setter(True)
        os.system(admin)
        print("chrome is opening, please wait...")
        await asyncio.sleep(15)
    else:
        print("chrome already opened")
        return False

    return True


async def chrome_status_setter(status):
    test = open(chrome_status, "w+")
    if status:
        process_name = "chrome.exe"
        for proc in psutil.process_iter():
            if proc.name() == process_name:
                test.write(str(proc) + "\n")
    
    test.close()


async def chrome_status_checker():
    test = open(chrome_status, "r+")
    status = test.read()
    process_name = "chrome.exe"
    true = []
    false = []
    for proc in psutil.process_iter():
        if proc.name() == process_name:
            if str(proc) in status:
                true.append(str(proc))
            else:
                false.append(str(proc))

    if len(true) > len(false):
        return True
    else:
        return False

in Automate.py

class Automate(object):
    def __init__(self):
        self.options = webdriver.ChromeOptions()
        loop_main = asyncio.new_event_loop()
        loop_main.run_until_complete(singleton.initialize())
        loop_main.close()
        self.options.add_argument('--user-data-dir=F:\\profile path')
        self.options.add_experimental_option('debuggerAddress', 'localhost:9222')
        self.driver = webdriver.Chrome(executable_path="F:\\driver path", options = self.options)

This worked for me. If there is a better and simple solution, please let me know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.