1. 程式人生 > >UI“三重天”之selenium--常用API和問題處理(三)

UI“三重天”之selenium--常用API和問題處理(三)

Selenium常用API:

前面兩篇示例程式碼中用到了一些selenium的API方法,例如定位元素的八種方法、訪問url、等待、操作瀏覽器、獲取title、點選、清理等等。

有關於selenium的常用API在園子中有寫的非常詳細的文章。先貼大佬文章地址:https://www.cnblogs.com/Ming8006/p/5727542.html#c1.5。

對於幾種用的比較多的地方再記錄一下:

等待:

  顯式等待:等待條件成立,再繼續執行

  示例程式碼中含有顯式等待: 

// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith("cheese!"); } });

  官方文件說明:An explicit wait is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.【一句話概括“等待條件發生,再繼續執行的程式碼”】 

WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement"))) 

  在丟擲TimeoutException之前最多等待10s,或者在10s發現元素則返回。ExpectedCondition函式返回型別為true或非null物件。

  在例項中無需例項化:

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

  

  隱式等待:通過設定的時長等待頁面元素載入完成,再執行;如果超過設定時間,則繼續執行。

  官方文件示例程式碼:

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

  隱式等待方法關鍵字:implicitlyWait,直接呼叫即可。

  該例項等待10s,10s內元素載入完成則繼續。

  

  強制等待:lang包下的Thread.sleep()方法,該方法應該也是debug用的最多的一種。

滑鼠懸浮:

  在定位元素時,通常有些元素需要執行滑鼠懸浮操作。

  使用action包下perform方法:  

    //滑鼠懸浮
    public void hover(String xpath) {
        Actions action = new Actions(driver);
        try {
            action.moveToElement(driver.findElement(By.xpath(xpath))).perform();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

檔案上傳:

  檔案上傳可直接使用sendkeys傳入需要上傳檔案的本地路徑即可。

  切記:使用該方法,定位到的元素該標籤必須是input型別、type=file屬性,滿足該條件即可用到該方法。  

driver.findElement(By.xpath(xpath)).sendKeys(filePath);

  filepath為本地檔案路徑及檔名。

截圖:

  通常執行自動化測試指令碼並非一帆風順,或者發現流程上的一些錯誤等等,這個時候便需要增加一些截圖,執行完成之後人為進行檢查。

  官方文件給出了示例程式碼:  

import java.net.URL;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {
    
    public void myTest() throws Exception {
        WebDriver driver = new RemoteWebDriver(
                                new URL("http://localhost:4444/wd/hub"), 
                                DesiredCapabilities.firefox());
        
        driver.get("http://www.google.com");
        
        // RemoteWebDriver does not implement the TakesScreenshot class
        // if the driver does have the Capabilities to take a screenshot
        // then Augmenter will add the TakesScreenshot methods to the instance
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshot = ((TakesScreenshot)augmentedDriver).
                            getScreenshotAs(OutputType.FILE);
    }
}

  可以看的出該處用到的是augment,中間的註釋指的是如果驅動程式確實有能力進行截圖,然後Augmenter會將TaksCyEnScript方法新增到例項中。

呼叫JS:

  有時候需要利用JS來執行賦值、點選操作等。

  使用的是JavascriptExecutor,copy一下上方連結那位大佬的示例程式碼。 

    private static void runJSTest1(WebDriver driver) throws InterruptedException {
        String js ="alert(\"hello,this is a alert!\")";
        ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js);
        Thread.sleep(2000);
    }
    
    private static void runJSTest2(WebDriver driver)
            throws InterruptedException {
        driver.get("https://www.baidu.com/");
        String js ="arguments[0].click();";
        driver.findElement(By.id("kw")).sendKeys("JAVA");
        WebElement searchButton = driver.findElement(By.id("su"));
        ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js,searchButton);
        Thread.sleep(2000);
    }

瀏覽器滾動:

  一樣使用的是JavascriptExecutor。  

JavascriptExecutor js = (JavascriptExecutor)driver;
String jscmd = "window.scrollTo(0," + height + ")";
            js.executeScript(jscmd);

進入iframe子頁面:

  通常一些元素會在iframe的標籤下,那麼便需要進入iframe再進行定位:  

WebElement frame = driver.findElement(By.xpath());
            driver.switchTo().frame();

下拉框:

  針對下拉框selenium使用select。  

Select userselect = new Select(driver.findElement(By.xpath()));
            userselect.selectByVisibleText();

切換瀏覽器視窗:

  webdriver中包含getWindowHandles方法。通過視窗標題去判斷切換瀏覽器的視窗  

    public void switchWindow(String target) {
        //建立 一個字串便於之後存放控制代碼
        String s = null;
        //獲取當前介面中的控制代碼
        Set<String> handles = driver.getWindowHandles();
        //迴圈嘗試,找到目標瀏覽器的控制代碼
        for(String t :handles) {
            //遍歷每一個控制代碼,判斷視窗的標題是否含有預期字元
            System.out.println(t);
            if (driver.switchTo().window(t).getTitle().equals(target)) {
                s = t;
            }
        }
        //切換到目標控制代碼的介面中
        try {
            driver.switchTo().window(s);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

載入cookie:

//addcookie方法
driver.manage.addcookie()
//使用option讀取使用者檔案,本地路徑 ChromeOptions o = new ChromeOptions(); o.addArguments(“本地路徑”)

 

後續~~~~