最近一直苦恼怎么动态调试已经打开了的浏览器!!,苦思冥想之后,想到了这个折中的办法~~
简单地说,就是程序之间的通讯来实现对已经打开的浏览器进行动态的调试!!
废话不多说,直接上代码
服务端:创建一个WebDriver实例:drive;reload(rpcclient)就是重新加载模块,主要是通过rpcclient里面的get函数来实现动态调试
#-*-coding:utf-8-*-
#-*-coding:utf-8-*-
#rpcserver.py
importpickle
fromselenium.webdriver.chrome.webdriverimportWebDriver
frommultiprocessing.connectionimportListener
fromthreadingimportThread
drive=WebDriver(executable_path="C:\chromedriver\chromedriver")
defrpc_server(handler,address,authkey):
sock=Listener(address,authkey=authkey)
whileTrue:
client=sock.accept()
t=Thread(target=handler.handle_connection,args=(client,))
t.daemon=True
t.start()
classRPCHandler(object):
def__init__(self):
#rpcfunctionsmap
self._functions={}
defregister_function(self,func):
self._functions[func.__name__]=func
defhandle_connection(self,connection):
try:
whileTrue:
#接收到一条消息,使用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))
exceptExceptionase:
connection.send(pickle.dumps(e))
exceptEOFError:
pass
if__name__=='__main__':
#写几个测试方法
defadd():
reload(rpcclient)
rpcclient.get(drive)
#新建一个handler类实例,并将add方法注册到handler里面
importrpcclient
fromimpimportreload
rpc_handler=RPCHandler()
rpc_handler.register_function(add)
#运行server
rpc_server(rpc_handler,('localhost',17001),authkey=b'tab_space')
客户端:里面的get方法,可以随时修改调试代码后进行运行
#-*-coding:utf-8-*-
importpickle
classRPCProxy(object):
def__init__(self,connection):
self._connection=connection
def__getattr__(self,name):
#通过name,得到一个函数
defdo_rpc(*args,**kwargs):
self._connection.send(pickle.dumps((name,args,kwargs)))
result=pickle.loads(self._connection.recv())
ifisinstance(result,Exception):
raiseresult
returnresult
returndo_rpc
defget(driver):
driver.find_elements_by_xpath("//span[contains(text(), '添加部门/单位')]")[0].click()
#远程连接并且调用
if__name__=='__main__':
frommultiprocessing.connectionimportClient
rpc_client=Client(('localhost',17000),authkey=b'tab_space')
proxy=RPCProxy(rpc_client)
b=proxy.add()
网友评论