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

参考文献:

1https://www.selenium.dev/zh-cn/

2https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/

3https://blog.csdn.net/kk_lzvvkpj/article/details/148610502

4https://registry.npmmirror.com/binary.html?path=chromedriver/

5https://chromedriver.chromium.org/

6https://www.runoob.com/selenium/selenium-mouse-and-keyboard-operation.html

相关推荐
卷无止境1 小时前
Python 异常处理:从入门到工程实践
后端·python
garuda herb1 小时前
生成专题页Blog--建立并返回 MySQL 数据库连接
python·mysql
ONE_SIX_MIX1 小时前
qwenpaw-plugin-file-tools QwenPaw增强文件工具 更新 v1.1.1
python·qwenpaw
AOwhisky1 小时前
Python 学习笔记(第五期)——组合数据类型:列表、元组、集合与字典精讲——核心知识点自测与详解
开发语言·笔记·python·学习·云计算
码农学院2 小时前
GEO与SEO协同:从传统搜索到生成式搜索的平滑迁移路径
服务器·前端·python
程序员羽痕2 小时前
基于 Django + PyTorch 的中文字体识别系统
pytorch·python·django
大模型码小白12 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
麻雀飞吧12 小时前
最新量化学习路径,交易认知和技术实现要并行
人工智能·python
C^h16 小时前
python函数学习
人工智能·python·机器学习
Fanta丶16 小时前
4.Python set()集合、dict(字典、映射)、 数据容器的通用功能
python