25+ Useful Selenium Web driver Code Snippets For GUI Testing Automation

本文總結了使用Selenium Web driver 作頁面自動化測試的一些 tips, tricks, snippets.javascript

 

1. Chrome Driver 如何安裝 extensions

兩種方式css

a) Packed (.crx file) --  crx爲Chrome的插件後綴名,FireFox的是xpihtml

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

 

b) Unpacked (directory)java

ChromeOptions options = new ChromeOptions();
options.addArguments("load-extension=/path/to/extension");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

 

2. 使用自定義的profile (即 user data directory)

由於WebDriver每次啓動一個實例時,會生成一個匿名的profile, 若是想用本身的profile (包括extensions, 還有settings), 能夠定義user data directory 路徑web

ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/user_name/AppData/Local/Google/Chrome/User Data");

 

3. 最大化窗口

網上有不少方式但好多試了都不行,下面這個是可行的chrome

        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");                
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);

 

4. 擺脫Google Analytics

因爲不少網頁嵌入Google Analytics, 這會致使Web Driver 訪問的時候超慢, 下載這個no_google_analytics-0.6-an+fx.xpi文件, FireFox的插件, Chrome的網上也有,參考這裏瀏覽器

            FirefoxProfile profile = new FirefoxProfile();
            profile.addExtension(new File(getClass().getClassLoader().getResource("no_google_analytics-0.6-an+fx.xpi").getFile()));
            desiredCapabilities.setCapability(FirefoxDriver.PROFILE, profile);

 

5. 設置代理

a) 不使用代理app

        FirefoxProfile firefoxProfile = new FirefoxProfile();
        firefoxProfile.setPreference("network.proxy.type", 0);
        driver = new FirefoxDriver(firefoxProfile);

 

b) 手動配置代理 httpide

        FirefoxProfile firefoxProfile = new FirefoxProfile();
        firefoxProfile.setPreference("network.proxy.type", 1);
        firefoxProfile.setPreference("network.proxy.http", "10.51.1.140");
        firefoxProfile.setPreference("network.proxy.http_port", "8080");
        driver = new FirefoxDriver(firefoxProfile); 

 

c) 自動代理配置學習

        FirefoxProfile firefoxProfile = new FirefoxProfile();
        profile.setPreference("network.proxy.type", 2);
        profile.setPreference("network.proxy.autoconfig_url", "http://proxy.xxx.net:8001"); //Auto config url
        driver = new FirefoxDriver(firefoxProfile);

 

##轉載註明出處:http://www.cnblogs.com/wade-xu/p/4846155.html 

 

6. 禁用image, javascript, css, document

        firefoxProfile.setPreference("permissions.default.image", 2);
        firefoxProfile.setPreference("permissions.default.script", 2);
        firefoxProfile.setPreference("permissions.default.stylesheet", 2);
        firefoxProfile.setPreference("permissions.default.subdocument", 2);

 

7. 上傳文件

String filePath = "path\\to\\file\for\\upload";
JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("document.getElementById('fileName').value='" + filePath + "';");

 

8. Frame切換

WebElement frameElement = driver.findElement(By.id("id-of-frame"));
driver.switchTo().frame(frameElement);

 

9. Get page source

String content = driver.getPageSource();

 

10. Get 頁面元素的 HTML source

JavascriptExecutor jsx = (JavascriptExecutor) driver;
String elementId = "element-id";
String html =(String) jsx.executeScript("return document.getElementById('" + elementId + "').innerHTML;");

##轉載註明出處:http://www.cnblogs.com/wade-xu/p/4846155.html  

 

11. Scroll Up, Down

JavascriptExecutor jsx = (JavascriptExecutor) driver;
//Vertical scroll - down by 100 pixels
jsx.executeScript("window.scrollBy(0,100)", "");
//Vertical scroll - up by 55 pixels (note the number is minus 55)
jsx.executeScript("window.scrollBy(0,-55)", "");

也能夠左右scroll

 

12. 多層菜單的處理

Actions actions = new Actions(driver);
WebElement menuElement = driver.findElement(By.id("menu-element-id"));
actions.moveToElement(menuElement).moveToElement(subMenuElement).click();

有些狀況下,move到一級菜單 須要等待一下子 才能定位到子菜單裏的選項,能夠thread sleep一下子

      actions.moveToElement(menuElement);
      Thread.sleep(1);
      actions.moveToElement(subMenuElement);
      Thread.sleep(1);
      actions.moveToElement(subSubMenuElement).click().perform();

 

13. 提取元素的 CSS 屬性

背景色, 文字顏色, 文字字號

String bgcolor = driver.findElement(By.id("id123")).getCssValue("background-color");

String textColor = driver.findElement(By.id("id123")).getCssValue("color");

String textFont = dr.findElement(By.tagName("h3")).getCssValue("font")

 

14. 很是特殊的一個輸入框

鼠標須要一直按在上面纔可定位到該元素,否則元素隱藏着,解決辦法用Action, moveToElement而後Click 輸入鍵盤動做Ctrl+A (全選)而後輸入數據,最後perform(), 全選輸入是爲了清除原來的數據

action.moveToElement(textSpan).click().sendKeys(Keys.chord(Keys.CONTROL, "a")).sendKeys(input).perform();

 

15. 執行JS命令直接Click button

有時候Button元素在頁面底部,屏幕只能顯示頁面上班部分, click不到元素, 這種方式任什麼時候候均可行。

((JavascriptExecutor)webDriver).executeScript("arguments[0].click();", webElement);

##轉載註明出處:http://www.cnblogs.com/wade-xu/p/4846155.html 

 

16. 取得頁面上全部的link

好比 html 以下

<div class="cities_boxer"> 
    <div class="left_side"> 
        <dl> 
               <dt>A</dt> 
                <dd> 
                        <a href="http://anshan.anjuke.com" class="">鞍山</a> 
                        <a href="http://anyang.anjuke.com" class="">安陽</a> 
                        <a href="http://anqing.anjuke.com" class="">安慶</a> 
                </dd> 
         </dl> 
    </div> 
</div>

 

        String link = null;
        List<WebElement> ls = driver.findElements(By.tagName("a"));
        List<String> links = new ArrayList<String>();
        for (WebElement a : ls) {
            link = a.getAttribute("href");
            links.add(link);
        }
        

 

17. 查找最後一個子節點

好比瀏覽器F12 控制檯輸入

$$('.cities_boxer > div.left_side > dl:nth-child(1) > dd > a:nth-last-child(1)')

返回 <a href="http://anshun.anjuke.com" class="">安順</a>

注: $$() Returns an array of all the elements that match the specified CSS selector. 

 

另外一種方式

$x("//*[@id='content']/div[4]/div[1]/dl[1]/dd/a[last()]")

注:$x() Returns an array of elements that match the specified XPath.

 

測試站點:http://www.anjuke.com/sy-city.html

 

 18. 等待 FluentWait

wait =  new FluentWait<WebDriver>(webDriver).withTimeout(10, TimeUnit.SECONDS) 
              .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

In FluentWait you have more options to configure apart from Maximum wait time like polling interval, exceptions to ignore etc.

 

19. Take A Screenshot

File screenshot =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

 

20. WebDriverWait 等待元素的預期狀態

明確的等待是指在代碼進行下一步操做以前等待某一個條件的發生。最很差的狀況是使用Thread.sleep()去設置一段確認的時間去等待。
爲何說最很差呢?由於一個元素的加載時間有長有短,你在設置sleep的時間以前要本身把握長短,過短容易超時,太長浪費時間。
selenium webdriver提供了一些方法幫助咱們等待正好須要等待的時間。利用WebDriverWait類和ExpectedCondition接口就能實現這一點。
    public void waitUntilBecomesVisible(WebElement webElement) {
        new WebDriverWait(webDriver, 10).until(ExpectedConditions.visibilityOf(webElement));
    }
    public void waitTextToBePresentInElement(WebElement element, String text) {
        new WebDriverWait(webDriver, 10).until(ExpectedConditions.textToBePresentInElement(element, text));
    }
    public void waitUntilInvisible(By by) {
        new WebDriverWait(webDriver, 10).until(ExpectedConditions.invisibilityOfElementLocated(by));
    }
    public void WaitUntilClickable(WebElement element) {
        new WebDriverWait(webDriver, 10).until(ExpectedConditions.elementToBeClickable(element));
    }
 
 

21. 隱性等待

隱性等待是指當要查找元素,而這個元素沒有立刻出現時,告訴WebDriver查詢Dom必定時間。默認值是0, 可是設置以後,這個時間將在WebDriver對象實例整個生命週期都起做用。
 webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);

 

22. AjaxElementLocatorFactory

public class PageBase {
  public PageBase(WebDriver driver) {
    AjaxElementLocatorFactory finder = new AjaxElementLocatorFactory(driver, 10);
    PageFactory.initElements(finder, this);
  }
}

注: 經常使用於Web application 有不少Ajax組件元素

Selenium does comes with AjaxElementLocatorFactory, which creates instances of AjaxElementLocator. Now the idea is, if you send an Ajax request, this ElementLocator waits for 250 milliseconds to look for the element, till it ultimately times out (configurable). The only exposed API from Selenium, that I found, was PageFactory, whose main purpose is to create a DefaultElementLocatorFactory, which does not wait.

 

23. 彈出對話框

Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();
getText()    獲得它的文本值
accept()      至關於點擊它的"確認"
dismiss()     至關於點擊"取消"或者叉掉對話框
 

24. 拖拉(Drag andDrop)

WebElement element =driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();

 

25. WebDriver設置元素焦點

if("input".equals(element.getTagName()){
   element.sendKeys("");
} 
else{
   new Actions(driver).moveToElement(element).perform();
}

((JavascriptExecutor)webDriver).executeScript("document.getElementById('elementid').focus();");

 

##轉載註明出處:http://www.cnblogs.com/wade-xu/p/4846155.html 

 

26. 瀏覽器 Navigate Back And Forward

//Go back to the last visited page
driver.navigate().back();

//go forward to the next page
driver.navigate().forward();

 

27. Check If An Element Exists

driver.findElements(By.id("element-id")).size()!=0

 

28. Check If An Element Is Visible

WebElement element  = driver.findElement(By.id("element-id"));
if(element instanceof RenderedWebElement) {
System.out.println("Element visible");
} else {
System.out.println("Element Not visible");
}

 

感謝閱讀,若是您以爲本文的內容對您的學習有所幫助,您能夠點擊右下方的推薦按鈕,您的鼓勵是我創做的動力。 

##轉載註明出處:http://www.cnblogs.com/wade-xu/p/4846155.html 

相關文章
相關標籤/搜索