学习Python中Selenium模块的基本用法(18:使用ActionChains操作鼠标)

Selenium模块的ActionChains类支持模拟鼠标的单独操作及组合操作,其常用鼠标操作函数如下表所示:

序号 名称 说明
1 click 单击元素,如果不指定元素则点击当前鼠标位置
2 click_and_hold 在元素上按下鼠标左键(不松开)
3 double_click 双击元素
4 context_click 右击元素。
5 drag_and_drop drag_and_drop(source, target),将源元素拖放到目标元素
6 drag_and_drop_by_offset drag_and_drop_by_offset(source, xoffset, yoffset): 将源元素拖放到指定的偏移量
7 move_by_offset move_by_offset(xoffset, yoffset): 将鼠标从当前位置移动指定的偏移量
8 move_to_element 将鼠标移动到指定元素上
9 move_to_element_with_offset move_to_element_with_offset(to_element, xoffset, yoffset): 将鼠标移动到指定元素的指定偏移位置
10 release 释放按下的鼠标按钮

以登录新浪邮箱为例,将鼠标移动到用户名输入框,输入用户名后按回车切换到密码输入框,然后点击登录按钮。示例程序及运行效果如下所示:

python 复制代码
driver = webdriver.Chrome()
driver.get("https://mail.sina.com.cn/")

time.sleep(3)

username = driver.find_element(By.ID, "freename")
ActionChains(driver).move_to_element(username)\
                    .click()\
                    .send_keys("testusername")\
                    .send_keys(Keys.ENTER)\
                    .pause(1)\
                    .send_keys("testpassword")\
                    .perform()

time.sleep(1)
login_btn=driver.find_element(By.CLASS_NAME, "loginBtn")
ActionChains(driver).move_to_element(login_btn)\
                    .click()\
                    .perform()

参考文献:

1\]https://www.selenium.dev/zh-cn/ \[2\]https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/ \[3\]https://blog.csdn.net/kk_lzvvkpj/article/details/148610502 \[4\]https://registry.npmmirror.com/binary.html?path=chromedriver/ \[5\]https://chromedriver.chromium.org/ \[6\]https://www.runoob.com/selenium/selenium-mouse-and-keyboard-operation.html

相关推荐
飞翔的佩奇3 小时前
【完整源码+数据集+部署教程】【运动的&足球】足球比赛分析系统源码&数据集全套:改进yolo11-RFAConv
前端·python·yolo·计算机视觉·数据集·yolo11·足球比赛分析系统
智启七月3 小时前
Dexbotic 开源深度解析:重构具身智能 VLA 研发的技术基石与实现路径
人工智能·python
beyond阿亮4 小时前
nacos支持MCP Server注册与发现
java·python·ai·nacos·mcp
感哥4 小时前
Python 装饰器
python
快秃头的码农4 小时前
vscode搭建python项目隔离的虚拟环境
ide·vscode·python
mxpan4 小时前
从 0 到 1:用 Python 对接阿里云 DashScope,轻松实现 AI 对话功能
python·ai编程
被放养的研究生5 小时前
dir()与help()
python
我的xiaodoujiao5 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest
子不语1805 小时前
深度学习(一)——基础知识:Python语言/解释器/环境/编辑器
python·学习
爱学习的爬虫5 小时前
Python实现Jenkins实现自动化执行Job
python·自动化·jenkins