天天看點

java selenium_如何用selenium+java進行自動化測試

一、環境搭建

1、搭建好java環境,jdk要1.8及以上

2、安裝好ecplise

3、去selenium官網下載下傳selenium-server-standalone.jar包

java selenium_如何用selenium+java進行自動化測試

4、下載下傳對應浏覽器的web driver.exe 例如 谷歌浏覽器對應的是chromedriver.exe

5、在ecplise建立一個項目, 右鍵項目,

選擇Build Path --- Confige Build Path... --- Libraries --- Add JARs...,

之後再彈出框選擇目前項目下Tools檔案夾下的selenium-server-standalone-.jar,

然後點Apply and Close。

二、代碼例子

package selenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumTestChrome {

public static void main(String[] args) {

//通過以下方式加載ChromeDriver

System.setProperty("webdriver.chrome.driver","./Tools/chromedriver.exe");

//通過driver打開chrome首頁并通路百度

WebDriver driver = new ChromeDriver();

driver.get("https://www.baidu.com/");

//等待10s讓網頁完全加載

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

if(driver.findElement(By.id("kw")).isEnabled()){

driver.findElement(By.id("kw")).sendKeys("百度地圖");

driver.findElement(By.id("su")).click();

System.out.println("百度搜尋框可輸入搜尋");

}else{

System.out.println("百度搜尋輸入框不可編輯");

}

driver.quit();

}

}