1、从一个页面切换到另外一个页面时,里面点击控件会报控件找不到的错误,需要循环点击直到成功的那次才算完成;
#页面切换时的装饰器
def wait(func):
def waited(self, *args, **kwargs):
timeout = kwargs.get("timeout")
print("timeout: %d" % timeout)
result = None
start = time.time()
last = start
while time.time() - start < timeout:
try:
result = func(self, *args, **kwargs)
print("excuting %s success, break " % func.__name__)
break
except:
if time.time() - last > 4:
print("except: " + func.__name__)
print(traceback.format_exc())
last = time.time()
return result
return waited
class SDMS(object):
def __init__(self):
self.url = "http://shams171/sdms_portal/index.htm"
self.page = rpa.chrome.create(self.url)
@wait
def waitClick(self, page, ele, **kwargs):
page.click(ele)
def start():
sdms = SDMS()
sdms.waitClick(sdms.page, "新店", timeout=10)
上面是简化后的装饰器,之前写的装饰器太过复杂,造成每次写程序都不想用,所以需要简化后才觉得好用点。
比较复杂的装饰器如下:
'''
1、装饰器部分,循环等待,件不管是否出现,一直等到timeout才退出循环
2、wt_page = True,控件是浏览器类型; wt_page = False,控件是win32类型
'''
def waitDrapper(func):
def waitWrapper(obj, wt_ele, **kwargs):
wait_flag = False
value = ""
wt_page = kwargs.get("page")
wt_index = kwargs.get("index") if kwargs.get("index") else 1 # index默认为1
# kwargs中修改或者增加index的值
kwargs["index"] = wt_index
wt_timeout = kwargs.get("timeout") if kwargs.get("timeout") else 10
wt_logger = kwargs.get("mylogger")
# print(wt_ele);print(wt_page);print(wt_index);print(wt_timeout);print(wt_logger);
# 判断参数是否正确
if not wt_ele:
rpa.logger.error("element is none.")
return value
start = time.time()
last_time = start
while time.time() - start < wt_timeout:
if wt_page:
# page类型
try:
value = func(obj, wt_ele, **kwargs)
if wt_logger:
wt_logger.info("execute %s ( %s ) end." % (func.__name__, wt_ele))
rpa.logger.info("execute %s ( %s ) end." % (func.__name__, wt_ele))
break # 控件出现就break退出循环
except Exception:
rpa.logger.error(traceback.format_exc())
if not wt_page:
# win32类型
try:
value = func(obj, wt_ele, **kwargs)
if wt_logger:
wt_logger.info("executing %s ( %s ) end." % (func.__name__, wt_ele))
rpa.logger.info("executing %s ( %s ) end." % (func.__name__, wt_ele))
break # 控件出现就break退出循环
except Exception:
rpa.logger.error(traceback.format_exc())
sleep(1)
# 循环等待中,要打印等待提示信息;每过6秒打印一下;
if time.time() - last_time > 6:
if wt_logger:
wt_logger.info("waiting for %s." % wt_ele)
rpa.logger.info("waiting for %s." % wt_ele)
last_time = time.time()
return value
return waitWrapper