Preface
This article will introduce the ActionChains class in Selenium and how to use it to help you simulate the user's mouse and keyboard operations on the web page. Understand the common methods and sample codes of ActionChains, and you can easily implement operations such as moving the mouse, clicking on elements, and dragging elements. By studying this article, you can better apply ActionChains to solve problems in automated testing or web crawling.
Demo html file
<!DOCTYPE html>
<html>
<head>
<title>操作HTML示例</title>
<script>
function clickButton() {
var button = document.getElementById("clickButton");
button.click();
}
function doubleClickButton() {
var button = document.getElementById("doubleClickButton");
var event = new MouseEvent('dblclick', {
bubbles: true, cancelable: true });
button.dispatchEvent(event);
}
function initSlider() {
var slider_1 = document.getElementById("slider_1");
var isDragging = false;
var offset = {
x: 0, y: 0 };
slider_1.addEventListener("mousedown", startDrag);
slider_1.addEventListener("mouseup", stopDrag);
slider_1.addEventListener("mousemove", drag);
slider_1.addEventListener("mouseleave", stopDrag);
function startDrag(e) {
isDragging = true;
offset.x = e.clientX - slider_1.offsetLeft;
offset.y = e.clientY - slider_1.offsetTop;
}
function stopDrag() {
isDragging = false;
}
function drag(e) {
if (isDragging) {
var newX = e.clientX - offset.x;
var newY = e.clientY - offset.y;
slider_1.style.left = newX + "px";
slider_1.style.top = newY + "px";
}
}
}
function handleKeyUp(event) {
if (event.keyCode === 119) {
// F8键的keycode为119
alert("释放了F8键");
}
}
</script>
</head>
<body>
<h1>操作HTML示例</h1>
<button id="clickButton" onclick="alert('单击按钮')">单击按钮</button>
<button id="doubleClickButton" ondblclick="alert('双击按钮')">双击按钮</button>
<div>
<input id="slider" type="range" min="0" max="100" step="1" value="50" style="width: 200px;">
<input id="slider_2" type="range" min="0" max="100" step="1" value="50"
style="height: 200px; transform: rotate(270deg);">
</div>
<div id="box" style="width: 230px; height: 200px; background-color: lightblue; position: relative;">
<div id="slider_1"
style="width: 30px; height: 30px; background-color: red; position: absolute; top: 80px; left: 100px; cursor: move;">
</div>
</div>
<script>
window.addEventListener("load", initSlider);
window.addEventListener("keyup", handleKeyUp);
</script>
</body>
</html>
1. How to use
1. Method description
method | illustrate | parameter |
---|---|---|
move_to_element(element) | Move the mouse over the specified element | element: the target element to move to |
click() | Left click on the current mouse position | none |
click_and_hold() | Press and hold the left mouse button without releasing it | none |
release() | Release the left mouse button | none |
context_click() | Right click on current mouse location | none |
double_click() | Double-click the current mouse position | none |
drag_and_drop(source, target) | Drag an element from the source location to the target location | source: the source element to be dragged target: the target element to be dragged to |
drag_and_drop_by_offset(source, xoffset, yoffset) | Drag an element from the source position to the target position at a specified offset | source: the source element to be dragged xoffset: horizontal offset yoffset: vertical offset |
move_by_offset(xoffset, yoffset) | Moves the mouse by a specified offset relative to the current position | xoffset: horizontal offset yoffset: vertical offset |
key_down(value, element=None) | Simulate pressing a keyboard key to select a specified element | value: the keyboard key value to be pressed element (optional): the element to be operated on |
key_up(value, element=None) | Simulate releasing a keyboard key, optionally specifying elements | value: the keyboard key value to be released element (optional): the element to be operated on |
pause(seconds) | Pause execution for a while | seconds: pause time in seconds |
perform() | Execute a defined sequence of operations | none |
2. Left-click the current mouse position
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# 创建Chrome浏览器的WebDriver实例
driver = webdriver.Chrome()
# 最大化窗口
driver.maximize_window()
# 打开网页
driver.get("file:///C:/Users/admin/Desktop/Demo.html")
# 创建 actions 的 ActionChains 对象
actions = ActionChains(driver)
# 定位到需要点击的按钮
click = driver.find_element_by_css_selector('[id="clickButton"]')
# 将鼠标移动到按钮上
actions.move_to_element(click)
# 鼠标左键
actions.click()
# 执行操作(必须要有该方法,否则操作不会执行)
actions.perform()
# 简化代码
click = driver.find_element_by_css_selector('[id="clickButton"]')
ActionChains(driver).move_to_element(click).click().perform()
3. Double-click the current mouse position
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# 创建Chrome浏览器的WebDriver实例
driver = webdriver.Chrome()
# 最大化窗口
driver.maximize_window()
# 打开网页
driver.get("file:///C:/Users/admin/Desktop/Demo.html")
# 创建 actions 的 ActionChains 对象
actions = ActionChains(driver)
# 定位到需要点击的按钮
click = driver.find_element_by_css_selector('[id="doubleClickButton"]')
# 将鼠标移动到按钮上
actions.move_to_element(click)
# 鼠标双击
actions.double_click()
# 执行操作(必须要有该方法,否则操作不会执行)
actions.perform()
4. Drag the mouse to move elements
- scene one
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# 创建Chrome浏览器的WebDriver实例
driver = webdriver.Chrome()
# 最大化窗口
driver.maximize_window()
# 打开网页
driver.get("file:///C:/Users/admin/Desktop/Demo.html")
# 创建 actions 的 ActionChains 对象
actions = ActionChains(driver)
# 定位到需要拖拽的滑块元素
slider = driver.find_element_by_css_selector('[id="slider_1"]')
# 将鼠标移动到滑块上
actions.move_to_element(slider)
# 执行鼠标左键点击并按住不放
actions.click_and_hold()
# 设置每次移动的偏移量
offset = 7
# 模拟滑块的连续移动
for i in range(10):
# 向右移动 offset 像素
actions.move_by_offset(offset, 0)
actions.pause(0.1) # 添加暂停时间以控制移动速度
# 向左移动 offset 像素
for i in range(10):
actions.move_by_offset(-offset, 0)
actions.pause(0.1)
# 向下移动 offset 像素
for i in range(10):
actions.move_by_offset(0, offset)
actions.pause(0.1)
# 向上移动 offset 像素
for i in range(10):
actions.move_by_offset(0, -offset)
actions.pause(0.1)
# 释放鼠标左键
actions.release()
# 执行操作
actions.perform()
- Scene 2
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# 创建Chrome浏览器的WebDriver实例
driver = webdriver.Chrome()
# 最大化窗口
driver.maximize_window()
# 打开网页
driver.get("file:///C:/Users/admin/Desktop/Demo.html")
# 创建 actions 的 ActionChains 对象
actions = ActionChains(driver)
# 定位到需要拖拽的滑块元素
slider = driver.find_element_by_css_selector('[id="slider"]')
# 滑动到指定位置
actions.drag_and_drop_by_offset(slider, 80, 0)
# 定位到需要拖拽的滑块元素
slider_2 = driver.find_element_by_css_selector('[id="slider_2"]')
# 将鼠标移动到滑块上
actions.move_to_element(slider_2)
# 执行鼠标左键点击并按住不放
actions.click_and_hold()
# 滑动到指定位置
actions.move_by_offset(0, 50)
# 释放鼠标左键
actions.release()
# 执行操作
actions.perform()
5. Simulate keyboard keys
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
# 创建Chrome浏览器的WebDriver实例
driver = webdriver.Chrome()
# 最大化窗口
driver.maximize_window()
# 打开网页
driver.get("file:///C:/Users/admin/Desktop/Demo.html")
# 创建 actions 的 ActionChains 对象
actions = ActionChains(driver)
# 定位到需要拖拽的滑块元素
slider = driver.find_element_by_css_selector('[id="slider"]')
# 模拟按下右键,滑块移动. 键盘键码自行百度
actions.key_down(Keys.ARROW_RIGHT, slider)
# 模拟按下F8键
actions.key_down(Keys.F8)
# 模拟释放F8键
actions.key_up(Keys.F8)
# 执行操作
actions.perform()
6. Drop-down list scrolling
- Sample HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选择框</title>
<style>
/* 样式可根据需要自行修改 */
.select-box {
position: relative;
display: inline-block;
width: 150px;
height: 30px;
border: 1px solid #aaa;
}
.select-box:hover {
cursor: pointer;
}
.select-box > .selected-item {
display: block;
width: 100%;
height: 100%;
line-height: 30px;
padding: 0 10px;
}
.select-box > .options {
position: absolute;
top: 100%;
left: 0;
z-index: 99;
display: none;
width: 100%;
max-height: 200px;
overflow-y: auto;
border: 1px solid #aaa;
background-color: #fff;
}
.select-box > .options > div {
width: 100%;
height: 30px;
line-height: 30px;
padding: 0 10px;
}
.select-box > .options > div:hover {
background-color: #ccc;
cursor: pointer;
}
</style>
</head>
<body>
<div class="select-box">
<div class="selected-item">请选择</div>
<div class="options">
<div>选项1</div>
<div>选项2</div>
<div>选项3</div>
<div>选项4</div>
<div>选项5</div>
<div>选项6</div>
<div>选项7</div>
<div>选项8</div>
<div>选项9</div>
<div>选项10</div>
<div>选项11</div>
<div>选项12</div>
<div>选项13</div>
<div>选项14</div>
<div>选项15</div>
<div>选项16</div>
<div>选项17</div>
<div id="test">选项18</div>
<!-- 这里添加更多的选项 -->
</div>
</div>
<script>
var selectBox = document.querySelector('.select-box');
var selectedItem = selectBox.querySelector('.selected-item');
var options = selectBox.querySelector('.options');
// 点击选择框时,切换选项列表的显示/隐藏状态
selectBox.addEventListener('click', function() {
if (options.style.display === 'none' || options.style.display === '') {
options.style.display = 'block';
} else {
options.style.display = 'none';
}
});
// 点击选项时,将选项值赋值到选择框上方的文本框中,并隐藏选项列表
options.addEventListener('click', function(e) {
if (e.target.tagName.toLowerCase() === 'div') {
selectedItem.innerHTML = e.target.innerHTML;
// options.style.display = 'none';
}
});
</script>
</body>
</html>
- rolling method
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from time import sleep
# 创建Chrome浏览器的WebDriver实例
driver = webdriver.Chrome()
# 最大化窗口
driver.maximize_window()
# 打开网页
driver.get("file:///C:/Users/admin/Desktop/Demo.html")
# 点击展开下拉列表
driver.find_element(By.CSS_SELECTOR, '.selected-item').click()
# 定位到需要进行滚动的元素
element = driver.find_element(By.CSS_SELECTOR, '.options')
# 使用鼠标拖拽方式向下滚动10个像素,执行下面的滚动方式时,必须包含这个。
ActionChains(driver).move_to_element(element).click_and_hold().move_by_offset(0, 10).perform()
# 如以上方法使用有问题,就使用该方法
# ActionChains(driver).move_to_element(element).click_and_hold().move_by_offset(0, 10).release().perform()
sleep(3)
# 使用键盘按键方式滚动到页面底部
ActionChains(driver).move_to_element(element).send_keys(Keys.END).perform()
sleep(3)
# 使用键盘按键方式滚动到页面顶部
ActionChains(driver).move_to_element(element).send_keys(Keys.HOME).perform()
sleep(3)
# 使用键盘按键方式向下翻一页
ActionChains(driver).move_to_element(element).send_keys(Keys.PAGE_DOWN).perform()
sleep(3)
# 使用键盘按键方式向上翻一页
ActionChains(driver).move_to_element(element).send_keys(Keys.PAGE_UP).perform()
sleep(3)
# 关闭浏览器
driver.quit()