IDE(笔者使用IDEA )
Maven
浏览器(笔者使用Chrome)
?看你使用什么浏览器了,下载对应的驱动即可,此处以chrome为例,其他浏览器见此博客https://www.cnblogs.com/janson071/p/10439078.html。
官方下载地址http://chromedriver.storage.googleapis.com/index.html
感谢阿里开源计划,国内的用户也可以去淘宝镜像下载,http://npm.taobao.org/mirrors/chromedriver
注意:版本需要和你的浏览器版本一致。
下载好之后解压即可,放到一个好找的地方。
本次项目基于Selenium,官方网址https://www.selenium.dev/,打不打得开就看运气了。
中文网http://www.selenium.org.cn/,这个倒是打得开,不过没有官网的全面。
创建好maven项目导入下面依赖
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.14.0</version>
</dependency>
<!-- 与 selenium-java 版本要一致 -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>3.14.0</version>
</dependency>
package ink.zerohua;
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;
import java.util.Random;
public class TaoBaoLogin {
public static void main(String[] args) {
//此处填写驱动程序,前面是驱动名随浏览器改变,后面是你对应驱动程序的文件位置,我是绝对路径写法
System.setProperty(
"webdriver.chrome.driver",
"D:\\ideaProjects\\imitate_taobao_login\\src\\main\\resources\\driver\\ChromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//此处填写需要打开的网址,这是淘宝的登录网址
driver.get(
"https://login.taobao.com/member/login.jhtml");
// 你的用户名
String username = "your username";
// 你的密码
String password = "your password";
//通过选择器获取元素
WebElement usernameElement = driver.findElement(By.id("fm-login-id"));
// 模拟用户点击用户名输入框
usernameElement.click();
// 设置sleep,方便观察
Random rand = new Random();
try {
for (int i = 0; i < username.length(); i++) {
// 随机睡眠0-1秒
Thread.sleep(rand.nextInt(1000));
// 逐个输入单个字符
usernameElement.sendKeys("" + username.charAt(i));
}
WebElement passwordElement = driver.findElement(By.id("fm-login-password"));
passwordElement.click();
// 输入完成用户名后,随机睡眠0-3秒
Thread.sleep(rand.nextInt(3000));
for (int i = 0; i < password.length(); i++) {
Thread.sleep(rand.nextInt(1000));
passwordElement.sendKeys("" + password.charAt(i));
}
Actions action = new Actions(driver);
WebElement moveButton = driver.findElement(By.id("nc_1_n1z"));
// 移到滑块元素并悬停,不能超出框的长度,否则异常
action.clickAndHold(moveButton);
action.moveByOffset(258, 0).perform();
action.release();
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(300000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
driver.quit();
}
}
WebElement usernameElement = driver.findElement(By.id("fm-login-id"));
这个就和js一样,通过选择器获取元素,具体请看http://www.selenium.org.cn/1904.html
2020.6.9日测试成功,不知道以后会不会改。
如有错误或者建议,还请指出。
https://www.cnblogs.com/janson071/p/10439078.html
https://ask.csdn.net/questions/715089
https://www.cnblogs.com/iitxt/p/9015324.html
原文:https://www.cnblogs.com/zerohua/p/13081902.html