selenium之ActionChains鼠标连贯操作



一、ActionChains使用场景

当我们需要连贯操作时,就需要用到ActionChains模块了。


二、ActionChains用法及原理解析

ActionChains可以用来模拟一系列连贯的鼠标操作,鼠标移动、鼠标按钮操作、按键操作、上下文交互操作;比如鼠标单击、双击、右键、拖拽等。
官网使用方法举例:

# ActionChains can be used in a chain pattern:链式写法

menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()



# Or actions can be queued up one by one, then performed.:分步写法

menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()

查看ActionChains模块源码可以发现,ActionChains中的操作方法,会将操作放到self._actions(类型为list)队列中,并返回self实例本身,然后通过perform方法,依次执行队列中的操作。因此我们可以继续点出来类中的其他操作方法组成一个chains,然后通过perform()依次执行。

    def __init__(self, driver):
        """
        Creates a new ActionChains.

        :Args:
         - driver: The WebDriver instance which performs user actions.
        """
        self._driver = driver
        self._actions = []  # 列表,用于存放操作,调用的操作会追加到这个list中
        if self._driver.w3c:
            self.w3c_actions = ActionBuilder(driver)
            
    def perform(self):
        """
        Performs all stored actions.
        """
        if self._driver.w3c:
            self.w3c_actions.perform()
        else:
            for action in self._actions:  # 依次执行队列中的操作
                action()
                
    def click(self, on_element=None):
        """
        Clicks an element.

        :Args:
         - on_element: The element to click.
           If None, clicks on current mouse position.
        """
        if on_element:
            self.move_to_element(on_element)
        if self._driver.w3c:
            self.w3c_actions.pointer_action.click()
            self.w3c_actions.key_action.pause()
            self.w3c_actions.key_action.pause()
        else:
            self._actions.append(lambda: self._driver.execute(  # 将操作放到self._actions队列中,其他操作方法相同
                                 Command.CLICK, {'button': 0}))
        return self  #返回self实例本身



三、ActionChains包括的方法

ActionChains类中的操作方法解析
click(on_element=None)点击鼠标左键
click_and_hold(on_element=None)点击鼠标左键不松开
context_click(on_element=None)点击鼠标右键
double_click(on_element=None)双击鼠标左键
drag_and_drop(source, target)拖拽指定元素source,到指定target,并松开
drag_and_drop_by_offset(source, xoffset, yoffset)拖拽指定元素source到指定的x,y坐标,并松开
key_down(value, element=None)按下某个键盘上的键
key_up(value, element=None)松开某个键
move_by_offset(xoffset, yoffset)鼠标从当前位置移动到某个坐标
move_to_element(to_element)鼠标移动到指定元素的中间
move_to_element_with_offset(to_element, xoffset, yoffset)鼠标移动到距离指定元素x,y坐标的位置
pause(seconds)在指定时间内暂停所有的输入
perform()执行链中的所有动作
release(on_element=None)在某个元素位置松开鼠标左键
reset_actions()清除本地和远程端上已经存储的操作
send_keys(*keys_to_send)发送某些键到当前焦点的元素
send_keys_to_element(element, *keys_to_send) 发送某些键到指定元素



selenium3.14官网解释如下:

click(on_element=None)点击鼠标左键
Clicks an element.
Args :	
on_element: The element to click. If None, clicks on current mouse position.



click_and_hold(on_element=None)点击鼠标左键不松开
Holds down the left mouse button on an element.
Args :	
on_element: The element to mouse down. If None, clicks on current mouse position.



context_click(on_element=None)点击鼠标右键
Performs a context-click (right click) on an element.
Args :	
on_element: The element to context-click. If None, clicks on current mouse position.



double_click(on_element=None) 双击鼠标左键
Double-clicks an element.
Args :	
on_element: The element to double-click. If None, clicks on current mouse position.



drag_and_drop(source, target) 拖拽指定元素source,到指定target,并松开
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args :	
source: The element to mouse down.
target: The element to mouse up.



drag_and_drop_by_offset(source, xoffset, yoffset) 拖拽指定元素source到指定的x,y坐标,并松开
Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button.
Args :	
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.



key_down(value, element=None) 按下某个键盘上的键
Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args :	
value: The modifier key to send. Values are defined in Keys class.
element: The element to send keys. If None, sends a key to current focused element.

Example, pressing ctrl+c: 举例按下ctrl+c
ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()



key_up(value, element=None)  松开某个键
Releases a modifier key.
Args :	
value: The modifier key to send. Values are defined in Keys class.
element: The element to send keys. If None, sends a key to current focused element.



move_by_offset(xoffset, yoffset)  鼠标从当前位置移动到某个坐标
Moving the mouse to an offset from current mouse position.
Args :	
xoffset: X offset to move to, as a positive or negative integer.
yoffset: Y offset to move to, as a positive or negative integer.



move_to_element(to_element) 鼠标移动到指定元素的中间
Moving the mouse to the middle of an element.
Args :	
to_element: The WebElement to move to.



move_to_element_with_offset(to_element, xoffset, yoffset) 鼠标移动到距离指定元素x,y坐标的位置
Move the mouse by an offset of the specified element.
Offsets are relative to the top-left corner of the element.
Args :	
to_element: The WebElement to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.



pause(seconds)  在指定时间内暂停所有的输入
Pause all inputs for the specified duration in seconds



perform() 执行链中的所有动作
Performs all stored actions.



release(on_element=None) 在某个元素位置松开鼠标左键
Releasing a held mouse button on an element.
Args :	
on_element: The element to mouse up. If None, releases on current mouse position.



reset_actions() 清除本地和远程端上已经存储的操作
Clears actions that are already stored locally and on the remote end



send_keys(*keys_to_send) 发送某些键到当前焦点的元素
Sends keys to current focused element.
Args :	
keys_to_send: The keys to send. Modifier keys constants can be found in the ‘Keys’ class.



send_keys_to_element(element, *keys_to_send) 发送某些键到指定元素
Sends keys to an element.
Args :	
element: The element to send keys.
keys_to_send: The keys to send. Modifier keys constants can be found in the ‘Keys’ class.

参考文章:module-selenium.webdriver.common.action_chains

<think>好的,用户想了解如何使用Python和Selenium进行自动化测试中的鼠标和键盘操作。我需要根据提供的引用内容来构建一个结构清晰的回答,同时生成相关问题。 首先,要确保回答符合用户的要求,包括导入ActionChains、常用鼠标操作和键盘操作。引用中的信息提供了关于双击、右键、拖放、长按以及输入文本的示例代码,我需要整理这些内容。 然后,需要检查是否有其他重要的鼠标或键盘操作未被提及,比如悬停、组合键等。可能需要补充这些内容,但根据现有引用,可能没有相关信息,所以需要保持现有内容。 接下来,按照用户的要求,回答需要分步骤说明,结构清晰。可能需要分为几个部分:准备工作、鼠标操作、键盘操作、综合应用示例等。 在生成相关问题部分,需要考虑用户可能感兴趣的扩展内容,比如异常处理、无头模式、跨浏览器测试等,这些在引用中没有提到,但属于常见问题。 需要确保所有代码示例正确,并且符合引用中的内容。例如,引用2提到了双击操作和右键操作,引用4提到了长按,引用3提到了输入文本,引用1提到了导包方法。 最后,注意使用中文回答,正确使用LaTeX格式(虽然这个问题可能不涉及数学公式,但如果有变量或代码内联,可能需要使用$...$),但根据用户的问题,可能不需要数学公式,所以重点放在代码块和结构上。 总结步骤: 1. 导包和初始化 2. 鼠标操作:单击、双击、右键、拖放、悬停、长按 3. 键盘操作:输入、组合键、清除内容 4. 综合示例 5. 注意事项 6. 相关问题 需要验证每个步骤的示例代码是否正确引用自提供的引用内容,并正确标注引用标识。例如,双击操作来自引用2和4,右键来自引用2,拖放可能来自引用2或4,输入文本来自引用3,长按来自引用4。 可能需要调整顺序,使各部分更连贯。同时,确保语言简洁明了,帮助用户逐步理解和应用这些操作。</think>### Python+Selenium自动化测试中的鼠标和键盘操作指南 #### 一、环境准备 1. 导入关键模块: ```python from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains # [^1][^2] ``` #### 二、鼠标操作详解 1. **基础点击操作**: ```python element = driver.find_element_by_id('element_id') # 左键单击(默认) element.click() # 双击操作(表单字段/图标激活) ActionChains(driver).double_click(element).perform() # # 右键点击(触发上下文菜单) ActionChains(driver).context_click(element).perform() # ``` 2. **高级交互操作**: ```python # 拖放操作(文件上传/元素排序) source = driver.find_element_by_id('source') target = driver.find_element_by_id('target') ActionChains(driver).drag_and_drop(source, target).perform() # [^4] # 悬停操作(显示二级菜单) menu = driver.find_element_by_class_name('dropdown') ActionChains(driver).move_to_element(menu).perform() # 长按操作(特殊场景触发) login_btn = driver.find_element_by_id('login') ActionChains(driver).click_and_hold(login_btn).perform() # ``` #### 三、键盘操作精要 ```python search_box = driver.find_element_by_class_name("s_ipt") # 基础输入 search_box.send_keys("测试文本") # [^3] # 组合键操作(跨平台兼容) search_box.send_keys(Keys.CONTROL + 'a') # 全选 search_box.send_keys(Keys.BACKSPACE) # 删除 # 特殊键位操作 search_box.send_keys(Keys.ENTER) # 回车提交 search_box.send_keys(Keys.TAB) # 切换焦点 ``` #### 四、综合应用实例 ```python # 登录操作自动化 driver.get('http://example.com/login') username = driver.find_element_by_id('username') password = driver.find_element_by_id('password') # 输入凭证 ActionChains(driver).send_keys_to_element(username, "admin").perform() password.send_keys("secret") # 模拟键盘操作提交 password.send_keys(Keys.RETURN) # [^4] ``` #### 五、关键注意事项 1. 操作前确保元素可见且可交互(可结合显式等待) 2. 复杂操作建议分步执行,使用`perform()`统一执行 3. 不同浏览器可能需要特定驱动配置 4. 注意处理可能出现的`ElementNotInteractableException`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值