官方网站: http://www.seleniumhq.org/ 官方代码仓库: https://github.com/SeleniumHQ/selenium |
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.4.0</version> </dependency> <!-- 大家平时找jar包可以在这个网站:https://mvnrepository.com/ 去查询,非常好用 --> |
package org.linuxsogood.reference.chp1.selenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; /** * Created by honway on 2017/6/14 10:44. * */ public class Demo1 { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\opt\\driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://192.168.0.227:7700/"); WebElement username = driver.findElement(By.xpath("//*[@id=\"loginForm\"]/div/div[2]/input")); username.sendKeys("123456"); WebElement passwd = driver.findElement(By.xpath("//*[@id=\"loginForm\"]/div/div[3]/input")); passwd.sendKeys("123456"); driver.findElement(By.xpath("//*[@id=\"loginForm\"]/div/div[5]/button")).submit(); driver.findElement(By.xpath("//*[@id=\"menu_li\"]/li[2]/a")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"menu_li\"]/li[2]/ul/li[9]")).click(); } } |
对于每一种浏览器,都会有一个webDriver, 其实这个webDriver就是一个浏览器的驱动.用它来控制我们本地安装的对应的浏览器.我例子当中使用的是chrome的驱动器.
请注意:这里只需要设置驱动器对应的环境变量,不是你的chrome浏览器程序的exe文件所在的位置.是你下载的驱动器程序的位置.
附上官方的驱动器下载地址 http://chromedriver.storage.googleapis.com/index.html |
程序中有一个线程暂停了2秒的代码,是因为点击菜单,它有一个动画效果,如果不暂时一会儿再点击,就会选择不到元素,从而抛出异常.