本文总结了使用Selenium Web driver 做页面自动化测试的一些 tips, tricks, snippets.

1. Chrome Driver 如何安装 extensions

两种方式

a) Packed (.crx file) --  crx为Chrome的插件后缀名,FireFox的是xpi

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)

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 路径

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

3. 最大化窗口

网上有很多方式但好多试了都不行,下面这个是可行的

        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) 不使用代理

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

b) 手动配置代理 http

        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

25+ Useful Selenium Web driver Code Snippets For GUI Testing Automation的更多相关文章

  1. selenium web driver 使用JS修改input属性

    selenium获取input时候,发现type=”hidden” 的input无法修改value,经牛人指点,可以使用js修改 首先html源文件如下,设置为text .hidden.submit ...

  2. selenium web driver 配合使用testng

    首先为eclipse添加testng插件 步骤如下:help->Install New SoftWare... 2. 添加testng链接,该链接可以在这里找到 For the Eclipse ...

  3. selenium web driver 实现截图功能

    在验证某些关键步骤时,需要截个图来记录一下当时的情况 Webdriver截图时,需要引入 import java.io.File; import java.io.IOException; import ...

  4. selenium web driver

    WebDriver 支持的浏览器 IE6-10 FireFox大部分版本 Chrome Safari Opera Andrioid 系统上的自带浏览器 IOS系统上自带浏览器 HtmlUnit的无界面 ...

  5. Selenium Web 自动化 - 如何找到元素

    Selenium Web 自动化 - 如何找到元素 2016-07-29 1. 什么是元素? 元素:http://www.w3school.com.cn/html/html_elements.asp ...

  6. Selenium Web 自动化 - 项目实战(一)

    Selenium Web 自动化 - 测试框架(一) 2016-08-05 目录 1 框架结构雏形2 把Java项目转变成Maven项目3 加入TestNG配置文件4 Eclipse编码修改5 编写代 ...

  7. Selenium Web 自动化 - 项目实战(三)

    Selenium Web 自动化 - 项目实战(三) 2016-08-10 目录 1 关键字驱动概述2 框架更改总览3 框架更改详解  3.1 解析新增页面目录  3.2 解析新增测试用例目录  3. ...

  8. Selenium Web 自动化 - Selenium(Java)环境搭建

    Selenium Web 自动化 - Selenium(Java)环境搭建 2016-07-29 1 下载JDK JDK下载地址:http://www.oracle.com/technetwork/j ...

  9. Selenium Web 自动化 - Selenium常用API

    Selenium Web 自动化 - Selenium常用API 2016-08-01 目录 1 对浏览器操作  1.1 用webdriver打开一个浏览器  1.2 最大化浏览器&关闭浏览器 ...

随机推荐

  1. 如何制作快速加载的HTML页面

    整理出来的tip 减小页面的大小 在页面下载中,页面的大小至今扮演着非常重要的因素. 减小页面的大小能够通过排除不必要空格,注释,动态内嵌脚本,和放入外部文件的 CSS 等在页面结构中很小的改变都能够 ...

  2. (转)COM组件里的AddRef()

    D3D是 COM组件,它在服务进程中运行,而不在当前的客户进程中.在DX组件运行过程中,要创建一系列接口对象,如CreateDevice()返回接口指针,这些接口及其占用内存什么时候释放,要通过“引用 ...

  3. iOS设计模式和机制之观察者模式

    观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象.这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新自己. 观察者模式的思想:当某对象改变时,观察者会 ...

  4. QML Image: Cannot open: qrc:///new.pic.png

    初次遇到这个问题真有点摸不着头脑,于是乎百度一下咯,但是百度一向没有什么用,该有的没有,没用的回答倒是有特么一大堆. 自己解决: 我的解决方法很简答: 第一步:把图片放到当前路径下,也就是和.pro一 ...

  5. C#的循环语句

    1.输入月份,日期号,输出是见年的第几天. 循环语句: for 格式 for(初始条件;循环条件;状态改变) { 循环体,执行代码(break;跳出循环体) } 2.一个游戏,前20关是每一关自身的分 ...

  6. equals()和hashCode()隐式调用时的约定

    package com.hash; import java.util.HashMap; public class Apple { private String color; public Apple( ...

  7. 修复PHP在64位下序列化(serialize)的字符串在32位机器下反序列

    32机器下PHP 整型数值的范围最大不超过2147483647,而有些超出范围的数值在64序列化好的数据标识为整型,在反序列时就可能会出错. 尝试使用以下的办法可以修复此问题 function int ...

  8. Robot Test Framework + Selenium 的几个坑

    现有的webtest是基于Robot 和 Selenium 来写的,没出问题的时候还挺好的,出了问题想debug介个麻烦啊(也可能是姿势不对), 特罗列如下,如有不对,求指正,指导. 1. RIDE ...

  9. 强制span不换行

    对于上一篇提到的overflow的问题我好像搞懂一些了.事情大概是这个样子的:如果用了float属性,那么元素就会脱离文本的束缚,无法无天起来,这肯定是猿类无法忍受的.要想让他们乖乖就范,要么用清除浮 ...

  10. 跳过IE10安装VS2013

    @ECHO OFF :IE10HACK REG ADD "HKLM\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer" /v Ver ...