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

相关推荐
Lululaurel3 小时前
从静态图表到交互叙事:数据可视化的新范式与实现
python·信息可视化·数据分析·matplotlib·数据可视化
蒋星熠3 小时前
TensorFlow与PyTorch深度对比分析:从基础原理到实战选择的完整指南
人工智能·pytorch·python·深度学习·ai·tensorflow·neo4j
qq_340474023 小时前
0.1 tensorflow例1-梯度下降法
人工智能·python·tensorflow
紫钺-高山仰止3 小时前
【Pyzmq】python 跨进程线程通信 跨平台跨服务器通信
服务器·python·github
java1234_小锋3 小时前
[免费]基于Python的在线音乐网站系统(后端Django)【论文+源码+SQL脚本】
python·在线音乐·django音乐·python音乐·python在线音乐
无垠的广袤4 小时前
【LattePanda Mu 开发套件】AI 图像识别网页服务器
服务器·人工智能·python·单片机·嵌入式硬件·物联网
Derrick__15 小时前
Python常用三方模块——Pillow
开发语言·python·pillow
小蕾Java5 小时前
PyCharm保姆级详细使用手册(Python新手快速上手篇)
ide·python·pycharm
阿星_5 小时前
PyCharm项目依赖库的备份与还原方法
linux·服务器·python