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

相关推荐
Q_Q5110082855 分钟前
python+uniapp基于微信小程序的垃圾分类信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
HackerTom7 分钟前
vs code jupyter连gpu结点kernel
python·jupyter·gpu·vs code·远程
weixin_468466851 小时前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题
Nina_7171 小时前
pytorch核心组件以及流程
人工智能·pytorch·python
Highcharts.js2 小时前
在Python中配置高度交互的数据可视化:Highcharts完全指南
开发语言·python·信息可视化·highcharts
Ace_31750887762 小时前
京东关键字搜索接口逆向:从动态签名破解到分布式请求调度
分布式·python
yachuan_qiao2 小时前
专业的建筑设备监控管理系统选哪家
大数据·运维·python
l1t3 小时前
DeepSeek辅助编写转换DuckDB json格式执行计划到PostgreSQL格式的Python程序
数据库·python·postgresql·json·执行计划
q***82913 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
李昊哲小课3 小时前
cuda12 cudnn9 tensorflow 显卡加速
人工智能·python·深度学习·机器学习·tensorflow