def highlight(func):
def apply_style(element):
# 实现的方式很简单,就是定位到元素后,执行js样式
driver.execute_script("arguments[0].style.border='6px solid red'", element)
@wraps(func)
def wrapper(self, *args, **kwargs):
element = func(self, *args, **kwargs)
apply_style(element)
return element
return wrapper
def screenshot(func):
def screen_shot(screen_name):
driver.save_screenshot(screen_name)
@wraps(func)
def wrapper(self, *args, **kwargs):
element = func(self, *args, **kwargs)
screen_shot(str(args[-1]) + '.jpg') # 默认是以定位元素属性为文件名
return element
return wrapper
class Action(object):
def __init__(self, driver):
self.driver = driver
@screenshot
@highlight
def find_element(self, *loc):
try:
WebDriverWait(self.driver, 15).until(lambda driver: driver.find_element(*loc).is_displayed())
return self.driver.find_element(*loc)
except Exception as e:
return e
driver = webdriver.Chrome()
driver.get('http://www.baidu.com')
action = Action(driver)
action.find_element(By.ID, 'su')
time.sleep(3)
driver.quit()
def highlight(element, element_name=None, debug=True):
'''
:param element:定位到的元素对象
:param debug:开关截图功能,默认为True开启截图功能
:param element_name: 截图保存图片的名字,不传时,默认用before after作为图片名
'''
# 高亮元素
def apply_style():
driver.execute_script("arguments[0].style.border='6px solid red'", element)
# 截图
def screen_shot(screen_name):
driver.save_screenshot(screen_name)
if debug:
try:
screen_shot(str(element_name) + '_before.jpg')
apply_style()
screen_shot(str(element_name) + '_after.jpg')
except Exception as e:
return e
apply_style()
# 使用也很简单
element = driver.find_element(By.ID, 'kw')
highlight(element, 'kw')
还有可以改进的地方,就这些,希望对你有帮助。O(∩_∩) O