Web自动化测试中12306登陆中想着模拟鼠标去拖动滑块完成验证,试了很久发现了一种方法可以来绕过浏览器的检测来完成验证.
话不多说,直接上图和代码
selenium我用的是3.多的版本,如果是4.多的版本定位元素语法可能是:
driver.findElement(By.id("J-login"));
首先是所需要的的导入的jar包
下面是主方法:
package com.zmy.Test;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class WebAnto_12306 {
public static void main(String[] args) throws InterruptedException {
// 配置谷歌驱动
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
// 驱动自动控制软件标识
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-blink-features=AutomationControlled");
options.setExperimentalOption("excludeSwitches", new String[] { "enable-automation" });
// 创建驱动对象
ChromeDriver driver = new ChromeDriver(options);
// 窗口最大化
driver.manage().window().maximize();
// 隐式等待10s
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// 打开12306官网
driver.get("https://www.12306.cn/index/");
// 找到登录按钮并点击
driver.findElementById("J-btn-login").click();
// 找到用户名输入框并输入
driver.findElementById("J-userName").sendKeys("175********");
// 找到密码输入框
driver.findElementById("J-password").sendKeys("zhang******");
// 找到登陆按钮并点击
driver.findElementById("J-login").click();
// 找到拖动按钮
WebElement btnElement = driver.findElementById("nc_1_n1z");
// 创建动作对象
Actions actions = new Actions(driver);
// 按住鼠标
actions.clickAndHold(btnElement);
// 拖到最右边
actions.moveByOffset(400, 0);
//放开鼠标
actions.release();
// 执行该动作
actions.perform();
}
}
下面图片中的两个框框是成功的关键,可以试着去将第一个框框中options中add和set两个注释啦,你会有意外的发现
第二个框中的拖到最右边的来两个参数是,第一个是x轴,以拖动按钮作为中心水平是x轴,竖直是y轴向右移动400像素(qq截图就可以查看这个拖动框的长宽),上下不需要动.接着直接运行你会发现他可以自己模拟鼠标拖动啦.