zoukankan      html  css  js  c++  java
  • python+selenium-UI自动化之鼠标操作(转)

    一、前提

    导入鼠标操作的包
    1 from selenium.webdriver.common.action_chains import Action

    二、常用语法

    单击鼠标左键 :click(on_element=None)
    
    单击鼠标右键:context_click(on_element=None)
    
    单击鼠标左键不松开:click_and_hold(on_element=None) 
    
    双击鼠标左键:double_click(on_element=None) 
    
    将鼠标从某个元素(source)按下去拖拽到某个元素(target)然后松开:drag_and_drop(source, target)
    
    将鼠标从某个元素(source)拖拽到某个坐标然后松开:drag_and_drop_by_offset(source, xoffset, yoffset)
    
    鼠标从当前位置移动到某个坐标:move_by_offset(xoffset, yoffset) 
    
    鼠标移动到某个元素:move_to_element(to_element)
    
    移动到距某个元素(左上角坐标)多少距离的位置:move_to_element_with_offset(to_element, xoffset, yoffset)
    
    在某个元素位置松开鼠标左键:release(on_element=None)
    
    执行链条中所有操作:perform() 
    

    三、操作步骤

    1、定位元素或坐标

    2、选择合适的操作(可以多个操作组合)

    3、执行perform()

    四、示例

    示例1:鼠标移动到某个元素,左键点击,右键点击,双击
    示例网站:http://westcomb.cn/demo/

     1 from selenium import webdriver
     2 from time import sleep
     3 from selenium.webdriver.common.action_chains import ActionChains
     4 #打开浏览器
     5 driver = webdriver.Chrome()
     6 #打开网址
     7 driver.get("http://westcomb.cn/demo/")
     8 #找到元素
     9 ele = driver.find_element_by_link_text('Clicks Page')
    10 #点击元素,可以直接ele.click(),此处用鼠标的方法进行操作
    11 #鼠标移动至目标元素-点击目标元素-执行
    12 ActionChains(driver).move_to_element(ele).click().perform()
    13 #找到新的目标元素
    14 ele=driver.find_element_by_xpath('//div[@ondblclick="dcl(event)"]')
    15 #双击鼠标左键-执行
    16 ActionChains(driver).double_click(ele).perform()
    17 sleep(1)
    18 #找到新的目标元素
    19 ele=driver.find_element_by_xpath('//input[@value="right click me"]')
    20 #点击鼠标右键-执行
    21 ActionChains(driver).context_click(ele).perform()
    22 sleep(10)
    23 driver.quit()

    示例2:鼠标移动到某个坐标,左键按下不松,拖拽鼠标到指定位置再松开
    示例网站:http://www.atool9.com/canvas.php

     1 from selenium import webdriver
     2 from selenium.webdriver.common.action_chains import ActionChains
     3 from time import sleep
     4 driver=webdriver.Chrome()
     5 url="http://www.atool9.com/canvas.php"
     6 driver.get(url)
     7 #窗口最大化
     8 driver.maximize_window()
     9 #鼠标移动到指定位置(坐标)-执行
    10 ActionChains(driver).move_by_offset(300,300).perform()
    11 sleep(2)
    12 #鼠标左击不松开--有当前位置拖拽(分别在X轴,Y轴移动指定像素)-释放鼠标-执行
    13 ActionChains(driver).click_and_hold().move_by_offset(500,300).release().perform()
    14 sleep(5)
    15 driver.quit()
    16 driver.close()

    注意:多次执行move_by_offset(xoffset, yoffset) ,移动的坐标会累加,导致目标位置超出边界报错,所以要在多次移动之间加上ActionChains(driver).reset_actions()来清除坐标的累计

     
  • 相关阅读:
    django-02框架-配置、静态文件和路由
    django-01框架-工程搭建
    python虚拟环境安装
    linux推送文件到另一台主机
    python2问题收集
    python diff json方法
    Linux expect详解
    python scp到远端机器
    shell远程执行命令(命令行与脚本)
    git操作
  • 原文地址:https://www.cnblogs.com/nlyangtong/p/11889476.html
Copyright © 2011-2022 走看看