博客
关于我
Python+selenium —— UI自动化之鼠标操作
阅读量:798 次
发布时间:2023-03-07

本文共 1993 字,大约阅读时间需要 6 分钟。

以下是根据您的要求优化后的文章内容:


一、前提

为了实现鼠标操作,需要导入相应的包:

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)
  • 拖拽鼠标到目标元素并松开:
    drag_and_drop(source, target)
  • 拖拽鼠标到指定坐标并松开:
    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()

三、操作步骤

  • 定位元素或坐标

    使用定位策略(如 By.XPATH 或 By.CSS_SELECTOR)找到目标元素或使用绝对坐标。

  • 选择操作

    根据需求选择合适的鼠标操作,可以组合多个操作。

  • 执行操作链

    调用 perform() 方法执行所有操作。

  • 四、示例

    示例1:鼠标移动到元素,左键点击,右键点击,双击

    from selenium import webdriverfrom time import sleepfrom selenium.webdriver.common.action_chains import ActionChains# 打开浏览器driver = webdriver.Chrome()driver.get("http://westcomb.cn/demo/")# 找到目标元素ele = driver.find_element_by_link_text('Clicks Page')# 鼠标移动并点击ActionChains(driver).move_to_element(ele).click().perform()sleep(1)# 双击操作ele = driver.find_element_by_xpath('//div[@ondblclick="dcl(event)"]')ActionChains(driver).double_click(ele).perform()sleep(1)# 右键点击ele = driver.find_element_by_xpath('//input[@value="right click me"]')ActionChains(driver).context_click(ele).perform()sleep(10)# 关闭浏览器driver.quit()

    示例2:鼠标移动到坐标,左键按住拖拽

    from selenium import webdriverfrom time import sleepfrom selenium.webdriver.common.action_chains import ActionChains# 打开浏览器driver = webdriver.Chrome()driver.get("http://www.atool9.com/canvas.php")driver.maximize_window()# 移动到指定坐标ActionChains(driver).move_by_offset(300, 300).perform()sleep(2)# 左键按住并拖拽ActionChains(driver).click_and_hold().move_by_offset(500, 300).release().perform()sleep(5)# 关闭浏览器driver.quit()driver.close()

    注意事项

    • 多次 move_by_offset 会累加坐标,可能导致超出边界,建议在中间使用 reset_actions() 清除累计坐标。

    五、软件测试面试资源

    这份文章为您提供了关于Selenium鼠标操作的实用指南,帮助您更高效地执行复杂操作。我们也分享了阿里、腾讯、字节等一线互联网大厂的面试资料,供求职者参考。

    如果您觉得内容有用,请随时转发给有需要的朋友,共同进步!

    转载地址:http://igofk.baihongyu.com/

    你可能感兴趣的文章
    Python-如何使用FastAPI和uvicorn.run而不阻塞线程?
    查看>>
    Python-字典
    查看>>
    python-字符串
    查看>>
    Python-将二进制遮罩转换为多边形
    查看>>
    python-文件操作
    查看>>
    PYTHON-模块 sys os random shutil-练习
    查看>>
    Python-模块与包的管理
    查看>>
    PYTHON-模块定义 搜索路径
    查看>>
    Python-爬虫工程师-面试总结
    查看>>
    Python-类与文件读取结合
    查看>>
    python-类思想-实现简单增删查改
    查看>>
    python-网络编程
    查看>>
    python写入文件出现空行
    查看>>
    PYTHON-返回给定x的多边形路径的y坐标
    查看>>
    python-进程池与线程池,协程
    查看>>
    Python-通过函数传递变量
    查看>>
    Python内置函数详解——总结篇
    查看>>
    Python.对象集合中的标识.和散列
    查看>>
    Python.硒.拖放错误“AttributeError:move_to 需要 WebElement“
    查看>>
    Python内置函数详解
    查看>>