zoukankan      html  css  js  c++  java
  • python之selenium玩转鼠标操作(ActionChains)

    前提:

    一般人用selenium自动化时,会用到模拟鼠标操作的情况,像单击,双击,右击,左击啊等,这个时候我们就要用到ActionChains了。

    内容:

    1.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) ——拖拽到某个元素然后松开
    
        drag_and_drop_by_offset(source, xoffset, yoffset) ——拖拽到某个坐标然后松开
    
        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) ——移动到距某个元素(左上角坐标)多少距离的位置
    
        perform() ——执行链中的所有动作
    
        release(on_element=None) ——在某个元素位置松开鼠标左键
    
        send_keys(*keys_to_send) ——发送某个键到当前焦点的元素
    
        send_keys_to_element(element, *keys_to_send) ——发送某个键到指定元素

    2.ActionChains的用法

    了解了以上的方法,我们来将一下它的用法,它有两种写法:

    第一个是链式写法,顾名思义连在一起写:

    例子:

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    
    driver = webdriver.Chrome()
    driver.get("https://www.baidu.cn")
    
    # 定位到要悬停的元素
    above = driver.find_element_by_link_text("设置")
    # 对定位到的元素执行鼠标悬停操作
    ActionChains(driver).move_to_element(above).perform()

    第二个是分布式写发,顾名思义就是分开写:

    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    
    driver = webdriver.Chrome()
    driver.get("https://www.baidu.cn")
    
    # 定位到要悬停的元素
    above = driver.find_element_by_link_text("设置")
    # 对定位到的元素执行鼠标悬停操作
    action=ActionChains(driver)
    action.move_to_element(above)
    action.perform()
    • from selenium.webdriver import ActionChains

    导入提供鼠标操作的 ActionChains 类。

    • ActionChains(driver)

    调用 ActionChains()类, 将浏览器驱动 driver 作为参数传入。

    • move_to_element(above)

    context_click()方法用于模拟鼠标右键操作, 在调用时需要指定元素定位。

    • perform()

    执行所有 ActionChains 中存储的行为, 可以理解成是对整个操作的提交动作。

  • 相关阅读:
    java常用设计模式链接
    常用设计模式汇总
    转:面试的角度诠释Java工程师(二)
    转:面试的角度诠释Java工程师(一)
    神经网络与深度学习_邱锡鹏——无监督学习和信息论
    智能推荐算法在直播场景中的应用
    经纬度地点之间距离测算
    <3>Transformer 到bert 模型
    <4>从bert到XLnet
    <2>自然语言难在哪? ----刘知远教授
  • 原文地址:https://www.cnblogs.com/syayy/p/11724066.html
Copyright © 2011-2022 走看看