首页 > 解决方案 > 如何在不同的 python 文件中使用相同的 selenium web 驱动程序实例?

问题描述

我需要在不同的 python 文件中使用相同的 selenium web 驱动程序实例。这是我的基类。

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)

temp.py现在,当我尝试在两个不同的文件(如and )中为此类实例化一个对象时test.py

temp.py

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

test.py

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

结果是打开了两个单独的镀铬窗口。我希望这两个文件仅使用 Web 驱动程序的一个实例。我尝试寻找答案,有人说要使用单例类(我对单例类了解不多)。

有人可以给我一个关于如何在多个 python 文件中使用单个驱动程序实例的示例。

我想要什么: 我需要第一个文件来打开浏览器和第二个文件来发送命令,如 get,通过 xpath 查找元素。另外,我希望在不打开新浏览器窗口的情况下重新运行第二个文件。

标签: pythonseleniumselenium-chromedriversingleton

解决方案


我通过使用 chrome 远程调试找到了解决问题的方法。首先,我用这段代码检查了 chrome 是否正在运行。我知道这很少,但无论如何,它对我有用。我创建了几个文件singleton.py,,admin_chrome.batchrome.bat

admin_chrome.bat

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

chrome.bat,

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

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

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)

这对我有用。如果有更好更简单的解决方案,请告诉我。


推荐阅读