Selenium Web 自動化 - Selenium(Java)環境搭建


Selenium Web 自動化 - Selenium(Java)環境搭建

2016-07-29

1 下載JDK

JDK下載地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

2 安裝和配置JDK

  1. 安裝目錄盡量不要有空格  D:\Java\jdk1.8.0_91; D:\Java\jre8
  2. 設置環境變量: “我的電腦”->右鍵->“屬性”->”高級系統設置”->"新建系統變量" JAVA_HOME:D:\Java\jdk1.8.0_91 Path: %JAVA_HOME%\bin 重啟計算機
  3. 驗證一下是否搭建成功 打開CMD,輸入java –version 

3 下載eclipse

eclipse下載地址:https://www.eclipse.org/downloads/packages/release/luna/sr2%20

4 下載selenium

selenium下載地址:http://www.seleniumhq.org/download/ 下載java版本的selenium,需要翻牆

5 將selenium類庫引入eclipse

  1. 打開eclipse,新建一個用戶自定義類庫,依次點擊菜單欄上的“Window”->“Preferences”->“Java”->“Build path”->“User Libraries”:
  2. 在用戶類庫界面點擊“New...”,命名為:selenium,然后點擊OK保存,
  3. 在用戶類庫界面點擊“Add External JARS...”,添加selenium-java-2.48.2.jar和libs

6 一個簡單的web自動化演示

  1. 打開eclipse,新建一個Java project,Projectname為FirstSeleniumDemo
  2. 選中seleniumdemo項目 ->右鍵 ->Build Path ->Add Libraries -> User Library ->Next –>勾選selenium ->點擊 Finish
  3. 首先我們在src目錄下,新建一個Java類,Package為SeleniumDemo,Name:FirstDemo
  4. 輸入如下代碼: 
package SeleniumDemo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;

public class FirstDemo {

    public static void main(String[] args) {
        //聲明一個火狐瀏覽器driver對象
        WebDriver driver = new FirefoxDriver();
        //打開360搜索
        driver.get("http://www.haosou.com/");
        
        //找到搜索框元素
        WebElement searchInput = driver.findElement(By.name("q"));
        //向搜索框輸入“selenium”
        searchInput.sendKeys("selenium");
        
        //找到搜索按鈕
        WebElement searchButton = driver.findElement(By.id("search-button"));
        //點擊搜索按鈕
        searchButton.click();
        try {
            //這里我們暫時用sleep方式等待頁面條狀,后續會講到如何智能等待
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        //跳轉之后的頁面關鍵字輸入框元素
        WebElement keywordInput = driver.findElement(By.id("keyword"));
        //驗證輸入框的內容是不是selenium
        //Assert.assertEquals(keywordInput.getAttribute("value"), "selenium");
        
        //關閉瀏覽器
        driver.quit();
    }
}

  5. 在eclipse中右鍵運行該程序“run as Java Application”

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM