学习webdriver已一段时间,网上的资料虽然丰富,但比较零散。因此,趁着有时间,顺便整理一下java+webdriver学习笔记。
开发环境:
- eclipse下载地址: http://www.eclipse.org/kepler/
- JDK 1.8下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html
- selenium jar包(在此采用maven管理)
- testng(在eclipse上添加该插件)
- maven
- 浏览器驱动(本人习惯使用chromedriver,速度快,兼容好)
在Eclipse中安装TestNG插件
1、打开eclipse–>help–>Install New Software–>Add,输入Name:TestNG和Location: http://beust.com/eclipse后,点击OK。
2、然后选中TestNG,单击Next安装
3、安装好TestNG后重启eclipse查看是否安装好,Help–>About Eclipse–>Installation Details
安装配置Maven
1.下载maven
2 配置maven环境变量
3.安装必须的插件 maven integration for eclipse
4 打开Eclipse菜单栏->Help->Eclipse Marketplace… 如图:5.搜索” maven integration for eclipse”安装,如图,点击install安装会重启Eclipse
6.重启之后在Eclipse菜单栏->Window->Preferences点击打开,找到maven项,这个地地方需要配置2个地方(如图):
一、 Installations,点击Add,指向第三部中下载的maven的目录,比如我的是e:\Dev\appache\maven(就是maven home路径),指定成功以后 下图中的Global Settings from installation diectory会自动定位到maven所在路径下的conf/settings.xml文件(settings.xml是maven的设置配置文件,它可以指定本地仓库的存放路径、可以指定远程中央仓库的地址)二、User Settings: 用户设置(User Settings)这里会再次指定一个settings.xml这里是相当于局部变量,对当前用户适用,刚才前面的settings.xml是全局变量 针对所有用户。
由于前面我提供的settings.xml指定了本地仓库的路径为:e:\Dev\apache\maven\repo\m2这个是maven的目录下的,如果repo\m2目录不存在,请自建,然后把settings.xml文件放入repo目录 作为 user settings的配置文件。如果想更改本地仓库目录,请修改刚才提供的settings.xml文件中的:
E:/Dev/apache/maven/repo/m2 即可添加依赖包
testng依赖包:
Selenium依赖包:
示例:
package org.testng.reportng;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.testng.annotations.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
public class test {
public static WebDriver driver;
@BeforeMethod
public void beforeMethod() {
//自定义浏览器驱动chromedriver.exe的路径,若放在机器的C:\Windows\System32目录下,则下面一行可免
System.setProperty("webdriver.chrome.driver",
"D:\\eclipsework\\test\\driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@Test
public void send_weibo() throws InterruptedException {
driver.get("http://www.qq.com/");
Thread.sleep(3000);
WebElement e = driver.findElement(By.cssSelector("#todaytop a"));
String content = e.getText();
String link = e.getAttribute("href");
System.out.println(content);
System.out.println(link);
}
@AfterMethod
public void afterMethod() {
driver.quit();
}
}