python - 如何在不同的 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 查找元素。另外,我希望在不打开新浏览器窗口的情况下重新运行第二个文件。
解决方案
我通过使用 chrome 远程调试找到了解决问题的方法。首先,我用这段代码检查了 chrome 是否正在运行。我知道这很少,但无论如何,它对我有用。我创建了几个文件singleton.py
,,admin_chrome.bat
chrome.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)
这对我有用。如果有更好更简单的解决方案,请告诉我。
推荐阅读
- python - 在 django rest 框架中返回一个生成的 HTML 文件
- c - C - 如何添加多个标志
- c# - C# 优化 xml 到多级节点类型上的字典
- python - 我怎样才能用零正确填充一个 numpy 数组?
- php - 在 php 项目中,ajax 中的引导程序不起作用
- c++ - 在 createddialog 创建的窗口中捕获 OnMouseMove 消息以进行编辑控件?
- ios - 在 Swift 中,如何重用 UIVIewController 中的属性
- c - C函数在列表中插入项目
- javascript - 如何防止 contenteditable 输入事件并在 vue 中设置模型值?
- sql - 在 SSMS 中创建表并添加来自 2 个其他表的 2 条记录的乘法