学习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

相关推荐
a1117769 分钟前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得025 分钟前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
摘星编程3 小时前
OpenHarmony + RN:Calendar日期选择功能
python
Yvonne爱编码3 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python
一方_self3 小时前
了解和使用python的click命令行cli工具
开发语言·python
小芳矶3 小时前
Dify本地docker部署踩坑记录
python·docker·容器
2301_822366353 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
小郎君。4 小时前
【无标题】
python
喵手4 小时前
Python爬虫实战:数据治理实战 - 基于规则与模糊匹配的店铺/公司名实体消歧(附CSV导出 + SQLite持久化存储)!
爬虫·python·数据治理·爬虫实战·零基础python爬虫教学·规则与模糊匹配·店铺公司名实体消岐
喵手4 小时前
Python爬虫实战:国际电影节入围名单采集与智能分析系统:从数据抓取到获奖预测(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集数据csv导出·采集国际电影节入围名单·从数据抓取到获奖预测