自动化selenium 测试之道(二)

第二章 Selenium 初体验

2.1 Selenium -- 基于UI的Web 应用测试框架

     Web基础知识 -- HTML、Xpath、DOM、JavaScript

2.2 Selenium 组件

  • Selenium IDE: 录制回放。 Firefox浏览器的附加组件,
  • Selenium RC(Remote Control): java编写的服务端,通过处理脚本发送的HTTP请求,来操作浏览器
  • Selenium Grid:分布式测试,支持不同平台、不同浏览器的多台远程机器上同时运行测试脚
  • Selenium WebDriver:测试脚本的核心。在脚本中,通过调用Webdriver对象的方法来操作浏览器

(1)Selenium 1.0(IDE + RC + Grid)

(2)Selenium 2.0 (RC + WebDriver)

RC:测试脚本执行之前,需要启动Selenium 服务器,像客户端配置的代理一样,通过修改WebSite的源信息,绕过同源策略。

         通过注入JavaScript形成沙箱环境,完成测试脚本中制定的浏览器操作。

         适用于新的浏览器,WebDriver API无法支持得情况下。

WebDriver:通过调用浏览器原生接口来驱动,从浏览器外部控制。

2.3 Selenium IDE

      Firefox的一个插件。Firefox 55.0 以上版本不再支持。

      上手快,但是不能作为开发和维护复杂测试节课的解决方案。

2.4 Selenium WebDriver

      支持得脚本语言:Java、Python、Ruby、C#

  WedDriver的结构就是典型的C/S结构,WedDriver API相当于客户端,而小小的浏览器驱动才是服务器端。

  测试脚本通知浏览器要做的操作(WebDriver API)都包含于发送给Web Service的Http请求体中。

  这种请求是基于SessionId的,即不同WebDriver对象在多线程并行的时候不会有冲突和干扰。

2.4.2 元素定位

1. 使用DOM元素属性进行定位

  (1)ID  

<div id="pingxx">...</div>
WebElement element=driver.findElement(By.id("pingxx"));

(2)Name

<input name="pingxx" type="text"/>
WebElement element=driver.findElement(By.name("pingxx"));

(3)ClassName

<div class="test"><span>Pingxx</span></div><div class="test"><span>Gouda</span></div>
List<WebElement> tests=driver.findElements(By.className("test"));

(4)TagName

<iframe src="..."></iframe>
WebElement frame=driver.findElement(By.tagName("iframe"));

(5)LinkText

<a href="http://www.google.com/search? q=pingxx">searchPingxx</a>
WebElement cheese=driver.findElement(By.linkText("searchPingxx"));

(6)PartialLinkText

<a href="http://www.google.com/search? q=pingxx">search for Pingxx</a>
WebElement cheese=driver.findElement(By.partialLinkText("Pingxx"));

(7)CssSelector

<div id="food"> <span class="dairy">milk</span> <span class="dairy aged">cheese</span> </div>
WebElement cheese=driver.findElement(By.cssSelector("#food span.dairy.aged"));

(8)Xpath

<input type="text" name="example" />
<input type="text" name="other" />

List<WebElement> inputs=driver.findElements(By.xpath("//input"));

2. 如何选择定位方法

  (1)首选id

  注意:有些元素的id是动态的,页面刷新会改变

  (2)先找到一类元素,在通过具体的顺序位置定位某一个元素

  (3)Xpath or CssSelector

  性能不好,可读性不高,不好维护,依赖于元素位置

  (4)用JavaScript操作元素

2.4.4 Wait

  (1)显示等待:推荐

  明确等待条件,若条件满足,则不在等待,继续执行后续代码。可以设置等待时间,超时会抛出TimeoutException。

  超时时间内,WebDriver默认每500ms调用一次ExpectedCondition来确认元素。

  (2)隐式等待:

  对整个页面元素有效,会先设置等待时间,一直等待所有页面内容加载完成,直到超时再抛出异常。

2.4.4 常用的断言

  (1)常用断言

  (2)异常类型

  (3)UnitTest框架中的断言

2.5 Selenium Grid

2.5.1 工作原理

Selenium Grid允许同时并行地、在不同的环境上运行多个测试任务。

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/ppybear/p/12456418.html