• selenium中ActionChains方法详细讲解


    前言

       本文将介绍Selenium中的ActionChains类及其使用方法,帮助您模拟用户在网页上的鼠标和键盘操作。了解ActionChains的常用方法和示例代码,可轻松实现移动鼠标、点击元素、拖拽元素等操作。通过本文的学习,您能更好地应用ActionChains解决自动化测试或网页爬取中的问题。

    演示html文件

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    一、使用方法

    1、方法说明

    方法说明参数
    move_to_element(element)将鼠标移动到指定元素上方element: 要移动到的目标元素
    click()左键单击当前鼠标位置
    click_and_hold()按住并且不释放鼠标左键
    release()释放鼠标左键
    context_click()右键单击当前鼠标位置
    double_click()双击当前鼠标位置
    drag_and_drop(source, target)将一个元素从源位置拖拽到目标位置source: 要拖动的源元素
    target: 要拖动到的目标元素
    drag_and_drop_by_offset(source, xoffset, yoffset)将一个元素从源位置按指定偏移量拖拽到目标位置source: 要拖动的源元素
    xoffset: 横向偏移量
    yoffset: 纵向偏移量
    move_by_offset(xoffset, yoffset)将鼠标相对于当前位置按指定偏移量移动xoffset: 横向偏移量
    yoffset: 纵向偏移量
    key_down(value, element=None)模拟按下某个键盘按键,可选择指定元素value: 要按下的键盘按键值
    element(可选): 要操作的元素
    key_up(value, element=None)模拟释放某个键盘按键,可选择指定元素value: 要释放的键盘按键值
    element(可选): 要操作的元素
    pause(seconds)暂停执行一段时间seconds: 暂停的时间,单位为秒
    perform()执行已定义的操作序列

    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)
    
    # 定位到需要点击的按钮
    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    3、双击当前鼠标位置

    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    4、鼠标拖拽元素移动

    • 场景一
    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 场景二
    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    在这里插入图片描述

    5、模拟键盘按键

    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    6、下拉列表滚动

    • 示例HTML文件
    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>选项1div>
                <div>选项2div>
                <div>选项3div>
                <div>选项4div>
                <div>选项5div>
                <div>选项6div>
                <div>选项7div>
    			<div>选项8div>
    			<div>选项9div>
    			<div>选项10div>
    			<div>选项11div>
    			<div>选项12div>
    			<div>选项13div>
    			<div>选项14div>
    			<div>选项15div>
    			<div>选项16div>
    			<div>选项17div>
    			<div id="test">选项18div>
                
            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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 滚动方法
    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
  • 相关阅读:
    C#:实现平方数序列算法(附完整源码)
    102-视频与网络应用篇-环境搭建
    JS总结篇
    95后阿里P7晒出工资单:狠补了这些个技术栈,真的香啊
    论文解读(LightGCL)《LightGCL: Simple Yet Effective Graph Contrastive Learning for Recommendation》
    python Flask 缓存的两种方式
    【无标题】Web-Tomcat
    第一章习题
    Python+OpenCV裂缝面积识别系统(部署教程&源码)
    Attingo:西部数据部分SSD存在硬件设计制造缺陷
  • 原文地址:https://blog.csdn.net/qq_45664055/article/details/133029718