您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 > Selenium
使用selenium做自動化測試入門-基于JAVA
作者:網(wǎng)絡轉(zhuǎn)載 發(fā)布時間:[ 2017/6/15 14:40:54 ] 推薦標簽:功能測試工具 Selenium

  之前在使用JAVA做爬蟲的時候,有遇到一個問題,是有些網(wǎng)站,必須要瀏覽器運行,然后JS執(zhí)行.內(nèi)容才能顯示出來.遇到這種站,代碼直接趴了,內(nèi)容抓取不到.網(wǎng)上找了一下發(fā)現(xiàn)有一個叫selenium的,可以模擬瀏覽器行為,做自動化測試.感覺這個應該挺好玩的.難得有時間.玩了一把.確實不錯
  官方網(wǎng)站: http://www.seleniumhq.org/
  官方代碼倉庫: https://github.com/SeleniumHQ/selenium  
  我的項目使用的依賴管理工具是maven,下面給出Selenium的maven地址
          <dependency>
              <groupId>org.seleniumhq.selenium</groupId>
              <artifactId>selenium-java</artifactId>
              <version>3.4.0</version>
          </dependency>
  <!-- 大家平時找jar包可以在這個網(wǎng)站:https://mvnrepository.com/ 去查詢,非常好用 -->
   然后寫一個入門測試的程序
package org.linuxsogood.reference.chp1.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
/**
 * Created by honway on 2017/6/14 10:44.
 *
 */
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "C:\opt\driver\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://192.168.0.227:7700/");
        WebElement username = driver.findElement(By.xpath("//*[@id="loginForm"]/div/div[2]/input"));
        username.sendKeys("123456");
        WebElement passwd = driver.findElement(By.xpath("//*[@id="loginForm"]/div/div[3]/input"));
        passwd.sendKeys("123456");
        driver.findElement(By.xpath("//*[@id="loginForm"]/div/div[5]/button")).submit();
        driver.findElement(By.xpath("//*[@id="menu_li"]/li[2]/a")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("//*[@id="menu_li"]/li[2]/ul/li[9]")).click();
    }
}
   由于selenium的運行是基于瀏覽器的,所以這里要下載一個webdriver,把下載下來的webDriver放到一個目錄里面,然后使用System工具類設置一下系統(tǒng)變量,指向這個webDriver
  對于每一種瀏覽器,都會有一個webDriver, 其實這個webDriver是一個瀏覽器的驅(qū)動.用它來控制我們本地安裝的對應的瀏覽器.我例子當中使用的是chrome的驅(qū)動器.
  請注意:這里只需要設置驅(qū)動器對應的環(huán)境變量,不是你的chrome瀏覽器程序的exe文件所在的位置.是你下載的驅(qū)動器程序的位置.
附上官方的驅(qū)動器下載地址 http://chromedriver.storage.googleapis.com/index.html


  
  程序中有一個線程暫停了2秒的代碼,是因為點擊菜單,它有一個動畫效果,如果不暫時一會兒再點擊,會選擇不到元素,從而拋出異常.

軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd