本文使用chrome浏览器
1.pom:
<!-- 加载selenium包 --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.31.0</version> </dependency>
2.demo:打开chrome浏览器并最大化,输入百度地址进入百度搜索页面,在百度输入框输入csdn,点击搜索,最后关闭浏览器
public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","D:/chromedriver.exe"); // 设置浏览器的参数,使其不弹框提示(chrome正在受自动测试软件的控制) ChromeOptions options = new ChromeOptions(); options.addArguments("disable-infobars"); //定义驱动对象 WebDriver driver = new ChromeDriver(options); //打开网址 driver.get("http://www.baidu.com/"); //浏览器窗口最大化 driver.manage().window().maximize(); //定位输入框元素 WebElement txtbox = driver.findElement(By.id("kw")); //在百度输入框输入文本 txtbox.sendKeys("csdn"); //定位"百度一下"按钮元素 WebElement btn = driver.findElement(By.id("su")); //点击按钮 btn.click(); //获取title和URL地址并输入到控制台 String title=driver.getTitle(); String url=driver.getCurrentUrl(); System.out.println(title+":"+url); //关闭 driver.close(); }
3.报错:
The path to the chromedriver executable must be set by the webdriver.chrome.driver system property;
没有合适的驱动,驱动下载地址:https://npm.taobao.org/mirrors/chromedriver/2.9/ ,
下载后放到System.setProperty("webdriver.chrome.driver","D:/chromedriver.exe"); 中的地址里。
如有不对欢迎指正。