欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何使用Robot Framework与Selenium实现鼠标右键点击操作

最编程 2024-07-22 19:37:17
...

问题:WEB自动化的时候,想要加一个点击鼠标右键的功能,发现robotframework-selenium没有

解决方法1:于是上网找了一下,网上大多说的是修改原文件:

参考原文:https://blog.****.net/aisi0308/article/details/79309763

在....\site-packages\SeleniumLibrary\keywords的element.py中加入一个方法def right_click_element方法,代码如下:

@keyword
def right_click_element(self, locator):
ele = self.find_element(locator)
action = ActionChains(self.driver)
action.context_click(ele).perform()

然后重启RF

尝试了一下,此方法可行

解决方法2:但因为我们组是很多个测试机,如果要一个个去替换element.py文件就太麻烦了,所以尝试了一下,发现只要能获取到当前浏览器的会话和driver对象,就可以不需要在原文件上扩展,可以自己定义一个扩展库

参考上面的方式,做了一下实现

"""
扩展selenium的关键字
注意:
方法中获取浏览器的会话代码:BuiltIn().get_library_instance('Selenium2Library')
若在robot中引入的library是Selenium2Library,则get_library_instance参数填写Selenium2Library
若在robt中引入的library是SeleniumLibrary,则get_library_instance参数填写SeleniumLibrary
"""

from selenium.webdriver.common.action_chains import ActionChains
from robot.libraries.BuiltIn import BuiltIn
from SeleniumLibrary.keywords.screenshot import ScreenshotKeywords

class Selenium_Extended_Keywords:

def right_click_element(self, locator):
"""
鼠标右键点击元素
:param locator:元素定位路径
:return:无返回值
"""
# 获取当前浏览器的会话
session = BuiltIn().get_library_instance('Selenium2Library')
driver = session.driver
try:
ele = session.find_element(locator)
action = ActionChains(driver)
action.context_click(ele).perform()
except Exception as e:
# 捕捉异常,若失败,则调用截图功能
ScreenshotKeywords(session).capture_page_screenshot()
raise e