web自动化系列-selenium 的鼠标操作(十)

对于鼠标操作 ,我们可以通过click()方法进行点击操作 ,但是有些特殊场景下的操作 ,click()是无法完成的 ,比如 :我想进行鼠标悬停 、想进行鼠标拖拽 ,怎么办 ?

这个时候你用click()是无法完成的 ,为此selenium提供这样一个类 ,专门用于进行鼠标 操作 ,这个类叫ActionChains .

1.ActionChains介绍

python 复制代码
# 鼠标操作
"""
说明 : 主要针对鼠标的一些特殊操作 ,比如 :右键 ,悬停 、拖拽, 双击
导入 :from selenium.webdriver.common.action_chains impot ActionChains
功能(方法) :
    右键 :content_click(elem)         ,elem代表元素对象
    悬停 : move_to_element(elem)
    拖拽 : drag_and_drop(source,target)  source代表源 ,target代表目的地
    双击 : double_click(elem)
    执行 :perform()
说明 :进行鼠标操作后,必须要调用perform()执行方法才能真正的操作 ,否则鼠标是不会实现操作的。

操作步骤:
1. 导包 :from selenium.webdriver.common.action_chains impot ActionChains
2. 创建对象 : action = ActionChains(driver)  ,其中这个类的参数为driver对象 
3. 调用功能的方法  action.content_click(elem)  ,其中elem是要操作的元素
4.调用执行方法  : action.perform()

2.具体案例

需求:通过selenium完成对tpshop的注册操作,具体如下 :

  1. 在首页的登录按钮上进行鼠标右击

  2. 将鼠标悬停在家用电器上

代码示例:

python 复制代码
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains

# 1. 创建浏览器对象
driver = webdriver.Chrome()
driver.maximize_window()

# 2. 输入地址 :http://localhost
driver.get("http://localhost")

# 初始化对象
action = ActionChains(driver)

time.sleep(1)
# 执行操作 :鼠标右键
login_elem = driver.find_element_by_link_text("登录")
action.context_click(login_elem)

# 执行上面的操作
action.perform()

time.sleep(2)

# 执行操作 :悬停
elem = driver.find_element_by_css_selector("a[title='家用电器']")
action.move_to_element(elem)
action.perform()
相关推荐
l1t1 小时前
DeepSeek辅助利用搬移底层xml实现快速编辑xlsx文件的python程序
xml·开发语言·python·xlsx
大飞记Python1 小时前
部门管理|“编辑部门”功能实现(Django5零基础Web平台)
前端·数据库·python·django
查士丁尼·绵3 小时前
笔试-羊狼过河
python
摸鱼的老谭3 小时前
构建Agent该选Python还是Java ?
java·python·agent
鄃鳕4 小时前
python 字典 列表 类比c++【python】
c++·python
可触的未来,发芽的智生4 小时前
新奇特:黑猫警长的纳米世界,忆阻器与神经网络的智慧
javascript·人工智能·python·神经网络·架构
程序员三藏4 小时前
Jmeter接口测试与压力测试
自动化测试·软件测试·python·测试工具·jmeter·接口测试·压力测试
烛阴4 小时前
用 Python 揭秘 IP 地址背后的地理位置和信息
前端·python
大宝剑1704 小时前
python环境安装
开发语言·python
Element_南笙5 小时前
吴恩达新课程:Agentic AI(笔记2)
数据库·人工智能·笔记·python·深度学习·ui·自然语言处理