1.导包
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.14.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
2.驱动、浏览器配置
我这里使用的是FireFox,不要问我为啥不用Chrome,因为他被我玩坏了,FireFox对配置的要求还挺严格,要么是不启动浏览器,要么是启动了浏览器不自动跳转网页,建议使用我这套。
火狐浏览器及对应的驱动程序
3.Java代码
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.firefox.bin", "E:\\FireFox52\\firefox.exe");
System.setProperty("webdriver.gecko.driver", "E:\\geckodriver_0.20.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://login.taobao.com/member/login.jhtml");
//获取输入框元素,并输入值
driver.findElement(By.id("fm-login-id")).sendKeys("账号");
driver.findElement(By.id("fm-login-password")).sendKeys("密码");
//获取搜索元素,并点击
driver.findElement(By.xpath("//*[contains(text(),'登录')]/../button ")).click();
}
如果你想隐藏浏览器只需要把
WebDriver driver = new FirefoxDriver();
替换成
FirefoxOptions direfoxOptions=new FirefoxOptions();
direfoxOptions.addArguments("-headless");
WebDriver driver = new FirefoxDriver(direfoxOptions);
就可以了