selenium中分離頁面元素(一)

         可以將一個頁面或一類元素看做是一個頁面對象,一個頁面對象對應一個類,將元素對象的獲取定義在這一個類中,頁面的元素分別定義,然後分別調用,使用@FindBy(id="XX")、@CacheLookup、public WebElement XX,然後調用PageFactory.initElements()方法來初始化元素,如:將百度首頁的輸入框與搜索按扭這兩個元素分離,編寫BaiduPage類,本文使用java編寫

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

/*
 * 把百度首頁的輸入框與搜索按扭這兩個元素分離
 * 用PageFactory.initElements()方法來初始化元素
 */

public class BaiduPage {
	
	//定義百度首頁搜索的輸入框
	@FindBy(id="kw")
	@CacheLookup
	public WebElement keyword_input;
	
	//定義百度首頁搜索按扭
	@FindBy(id="su")
	@CacheLookup
	public WebElement search_button;
	
	//創建一個構造函數,並且調用PageFactory.initElements()方法來初始化元素,換句話說,將元素映射到我們定義好的變量上
	public BaiduPage(WebDriver driver) {
		PageFactory.initElements(driver, this);
	}	
}

1、@FindBy:這個定義了你所查找的元素是以什麼方式定位的,用id定位,就寫成:@FindBy(id="kw"),還有其它的幾種寫法:

  (1)、@FindBy(name="XX");

  (2)、@FindBy(className="XX");

  (3)、@FindBy(xpath="XX");

  (4)、@FindBy(css="XX");

  等等

2、@CacheLookup:意思是說找到元素之後將緩存元素,重複的使用這些元素,將使測試的速度大大加快

3、WebElement keyword_input:就是變量名

 

接下來我們寫一個測試類,分別調用BaiduPage類的keyword_input與search_button這兩個元素

import org.testng.annotations.Test;
import com.suning.encapsulation.BaiduPage;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;

public class BaiduPageTest {
	
	WebDriver driver;
  
  @Test
  public void f() {
	  //實例化BaiduPage對象
	  BaiduPage page = new BaiduPage(driver);
	  
	  //page調用BaiduPage類中keyword_input元素,然後使用元素的sendKeys方法向輸入框中輸入selenium
	  page.keyword_input.sendKeys("selenium");
	  
	  //page調用BaiduPage類中search_button元素,然後調用元素的click方法點擊搜索按扭
	  page.keyword_input.click();
  }
  
  @BeforeTest
  public void beforeTest() {
	  driver = new FirefoxDriver();
	  driver.manage().window().maximize();
	  driver.get("http://baidu.com");
  }

  @AfterTest
  public void afterTest() {
	  driver.quit();
  }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章