selenium中分離頁面元素(二)
阿新 • • 發佈:2018-12-09
將頁面元素封裝,外部通過對應方法來呼叫,看如下程式碼,本文使用java編寫
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class BaiduSeparatePage { // 定義百度首頁搜尋的輸入框 @FindBy(id = "kw") @CacheLookup private WebElement keyword_input; // 定義百度首頁搜尋按扭 @FindBy(id = "su") @CacheLookup private WebElement search_button; //定義測試地址 private final String url = "http://www.baidu.com"; WebDriver driver; //建立一個建構函式,並啟動firefox瀏覽器 public BaiduSeparatePage() { driver = new FirefoxDriver(); PageFactory.initElements(driver, this); } //開啟網址 public void openUrl() { driver.get(url); } //關閉瀏覽器 public void close() { driver.quit(); } //輸入關鍵字selenium並點選百度一下按扭 public void searchByKeyword() { keyword_input.sendKeys("selenium"); search_button.click(); } }
測試類呼叫方法
import org.testng.annotations.Test; import com.suning.encapsulation.BaiduSeparatePage; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; public class BaiduSeparatePageTest { @Test public void f() { //例項化頁面物件模型 BaiduSeparatePage hsp = new BaiduSeparatePage(); //呼叫方法 hsp.openUrl(); hsp.searchByKeyword(); hsp.close(); } }