selenium常用的鼠标操作

这篇博客详细介绍了在Selenium中进行常见鼠标操作的方法,包括基本的代码演示,并提醒在执行鼠标操作时,若元素未定位或缺少perform()方法,可能导致操作失败。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

selenium常用的出表操作

基本代码演示

package com.test.demo;

import com.test.Init_Page;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.testng.annotations.Test;

/**
 * @author Huangtian
 * @create 2019-03-11 14:39
 */
public class Action_Mouse extends Init_Page {
    @FindBy(id = "menu-head1")
    WebElement menu_head1;

    @Test
    public void action_mouse() {
        driver.get("https://www.ezcun.com/");
        super.setWindowMax();//父类创建了浏览器最大化的方法
        /**
         * 模拟鼠标操作 Actions 类
         */
        Actions action = new Actions(driver);
        //鼠标悬停
        action.moveToElement(menu_head1).perform();
        /**
         *  鼠标左击
         *  action.click().perform();
         *  鼠标右击
         *  action.contextClick().perform();
         *  鼠标双击
         *  action.doubleClick().perform();
         */
    }
}

tips:

当鼠标操作没有执行时,常见的原因除了是元素没有定位到,还有就是在少了perform()方法导致鼠标事件没有执行;

在Java中使用Selenium控制鼠标操作可以通过Actions类来实现。以下是一个简单的示例代码,演示了如何使用Selenium控制鼠标移动、点击和拖放操作: ```java import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class MouseControlExample { public static void main(String[] args) { // 设置 ChromeDriver 路径 System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); // 创建一个新的 WebDriver 实例 WebDriver driver = new ChromeDriver(); // 打开网页 driver.get("https://www.example.com"); // 定位到需要进行鼠标操作的元素 WebElement element = driver.findElement(By.id("element-id")); // 创建一个 Actions 对象 Actions actions = new Actions(driver); // 鼠标移动到元素上 actions.moveToElement(element).perform(); // 鼠标点击元素 actions.click().perform(); // 鼠标拖放操作示例 WebElement sourceElement = driver.findElement(By.id("source-element")); WebElement targetElement = driver.findElement(By.id("target-element")); actions.dragAndDrop(sourceElement, targetElement).perform(); // 关闭浏览器 driver.quit(); } } ``` 请确保已经正确设置了ChromeDriver的路径,并将"element-id"替换为需要操作的元素的ID。这个示例代码演示了移动到元素、点击元素和拖放操作的基本用法,你可以根据自己的需求进行修改和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值