jQuery选择器-WEB自动化测试提速之利剑

来源:互联网 发布:五子棋游戏c语言代码 编辑:程序博客网 时间:2024/04/29 04:21

目前WEB层面的自动测试脚本主流框架采用 webdriver、selenium等开源框架。但其在页面元素的定位效率上实在是不敢恭维。jQuery选择器的引入能够大大提高这一效率。

jQuery常用选择器:

1、基础选择器

名称说明举例#id根据元素Id选择$("divId") 选择ID为divId的元素element根据元素的名称选择,$("a") 选择所有<a>元素.class根据元素的css类选择$(".bgRed") 选择所用CSS类为bgRed的元素*选择所有元素$("*")选择页面所有元素selector1, 
selector2, 
selectorN
可以将几个选择器用","分隔开然后再拼成一个选择器字符串.会同时选中这几个选择器匹配的内容.$("#divId, a, .bgRed")
2、层次选择器

名称说明举例ancestor descendant使用"form input"的形式选中form中的所有input元素.即ancestor(祖先)为from, descendant(子孙)为input.$(".bgRed div") 选择CSS类为bgRed的元素中的所有<div>元素.parent > child选择parent的直接子节点child.  child必须包含在parent中并且父类是parent元素.$(".myList>li") 选择CSS类为myList元素中的直接子节点<li>对象.prev + nextprev和next是两个同级别的元素. 选中在prev元素后面的next元素.$("#hibiscus+img")选在id为hibiscus元素后面的img对象.prev ~ siblings 选择prev后面的根据siblings过滤的元素 
注:siblings是过滤器$("#someDiv~[title]")选择id为someDiv的对象后面所有带有title属性的元素
3、内容过滤器

名称说明举例:contains(text)匹配包含给定文本的元素查找所有包含 "John" 的 div 元素:$("div:contains('John')"):empty匹配所有不包含子元素或者文本的空元素查找所有不包含子元素或者文本的空元素:$("td:empty"):has(selector)匹配含有选择器所匹配的元素的元素给所有包含 p 元素的 div 元素添加一个 text 类: $("div:has(p)").addClass("test");:parent匹配含有子元素或者文本的元素查找所有含有子元素或者文本的 td 元素:$("td:parent")

框架中定义js 执行的方法:

module JqueryHelper
def jquery script
result = @driver.execute_script script
return nil if not script.start_with? 'return '
result
end


def pure_js_wait script
i = 0
10.times do
i = i+1
result = @driver.execute_script script
break if !!result
sleep 0.5
end
end
end

在元素定位方法中:

pure_js_wait "return $('#frame商品管理').contents().find('.searchbox > input').size() == 1;"
jquery "$('#frame商品管理').contents().find('.searchbox > input').focus();"
jquery "$('#frame商品管理').contents().find('.searchbox > input').val('#{value}');"

原创粉丝点击