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()
相关推荐
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时4 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊4 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1234 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero074 天前
Jev 与 Laya
python·语言模型