最近一直苦恼怎么动态调试已经打开了的浏览器!!,苦思冥想之后,想到了这个折中的办法~~
简单地说,就是程序之间的通讯来实现对已经打开的浏览器进行动态的调试!!
废话不多说,直接上代码
服务端:创建一个 WebDriver 实例:drive;reload(rpcclient) 就是重新加载模块,主要是通过 rpcclient 里面的 get 函数来实现动态调试
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# rpcserver.py
import pickle
from selenium.webdriver.chrome.webdriver import WebDriver
from multiprocessing.connection import Listener
from threading import Thread
drive = WebDriver(executable_path="C:\chromedriver\chromedriver")
def rpc_server(handler, address, authkey):
sock = Listener(address, authkey=authkey)
while True:
client = sock.accept()
t = Thread(target=handler.handle_connection, args=(client,))
t.daemon = True
t.start()
class RPCHandler(object):
def __init__(self):
# rpc functions map
self._functions = {}
def register_function(self, func):
self._functions[func.__name__] = func
def handle_connection(self, connection):
try:
while True:
# 接收到一条消息, 使用pickle协议编码
func_name, args, kwargs = pickle.loads(connection.recv())
# rpc调用函数,并返回结果
try:
r = self._functions[func_name](*args, **kwargs)
print(type(r))
connection.send(pickle.dumps(r))
except Exception as e:
connection.send(pickle.dumps(e))
except EOFError:
pass
if __name__ == '__main__':
# 写几个测试方法
def add():
reload(rpcclient)
rpcclient.get(drive)
# 新建一个handler类实例, 并将add方法注册到handler里面
import rpcclient
from imp import reload
rpc_handler = RPCHandler()
rpc_handler.register_function(add)
# 运行server
rpc_server(rpc_handler, ('localhost', 17001), authkey=b'tab_space')
客户端:里面的 get 方法,可以随时修改调试代码后进行运行
# -*- coding: utf-8 -*-
import pickle
class RPCProxy(object):
def __init__(self, connection):
self._connection = connection
def __getattr__(self, name):
# 通过name,得到一个函数
def do_rpc(*args, **kwargs):
self._connection.send(pickle.dumps((name, args, kwargs)))
result = pickle.loads(self._connection.recv())
if isinstance(result, Exception):
raise result
return result
return do_rpc
def get(driver):
driver.find_elements_by_xpath("//span[contains(text(), '添加部门/单位')]")[0].click()
# 远程连接并且调用
if __name__ == '__main__':
from multiprocessing.connection import Client
rpc_client = Client(('localhost', 17000), authkey=b'tab_space')
proxy = RPCProxy(rpc_client)
b = proxy.add()