以chrome爲例:
步驟如下:
- 1.資源下載
需要下載driver和chrome版本對應關係
1.1 資源下載
官網地址:http://docs.seleniumhq.org/download/
各個版本下載地址:http://selenium-release.storage.googleapis.com/index.html
各瀏覽器驅動下載地址:
Gecko driver : https://github.com/mozilla/geckodriver/releases
Chrome driver: http://chromedriver.storage.googleapis.com/index.html https://npm.taobao.org/mirrors/chromedriver
driver和chrome版本對應關係: https://blog.csdn.net/huilan_same/article/details/51896672
IE driver : http://selenium-release.storage.googleapis.com/index.html
Edge driver : https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Opera driver : https://github.com/operasoftware/operachromiumdriver/releases
Safari driver : https://developer.apple.com/library/content/releasenotes/General/WhatsNewInSafari/Introduction/Introduction.html
PhantomJS driver : http://phantomjs.org/
- 2.添加pom.xm文件
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.13.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.11.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.13.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.13.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
- Chrome運行
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\\Tools\\chromedriver.exe");
//初始化一個chrome瀏覽器實例,實例名稱叫driver
WebDriver driver = new ChromeDriver();
//最大化窗口
driver.manage().window().maximize();
//設置隱性等待時間
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
// get()打開一個站點
driver.get("https://www.baidu.com");
//getTitle()獲取當前頁面title的值
System.out.println("當前打開頁面的標題是: "+ driver.getTitle());
//關閉並退出瀏覽器
driver.quit();
}
- 元素定位
Selenium提供了8種定位方式。
id
name
class name
tag name
link text
partial link text
xpath
css selector
- 元素操作
clear() 清除文本
sendKeys(value) 模擬按鍵輸入
click() 單擊元素
submit() 用於提交表單
getSize() 返回元素的尺寸
getText() 獲取元素的文本
getAttribute(name) 獲得屬性值
isDisplayed() 設置該元素是否用戶可見
element.clear();