一、Selenium定位页面元素的方法
selenium提供如下强大的定位元素的方法。
* id=id
* name=name
* dom=javascriptExpression
* xpath=xpathExpression
* link=textPattern
* css=cssSelectorSyntax
1、通过ID,name选择元素 : 如selenium.type("id=q","百度"); selenium.type("name=search","百度")
2、link=根据链接文字来操作:如selenium.click("link=个人资料");
3、根据XPath来选择元素 :
* xpath=//img[@alt='The image alt text']
*xpath=//table[@id='table1']//tr[4]/td[2]
* xpath=//a[contains(@href,'#id1')]
* xpath=//a[contains(@href,'#id1')]/@class
* xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
* xpath=//input[@name='name2' and @value='yes']
* xpath=//*[text()="right"]
如:
selenium.type("xpath=//input[@name='user.email']",
"xxx@123.com"); //向input中type为text的栏位键入信息
selenium.check("xpath=//input[(@name='user.sex')and(@value='男')]");//向input中type为radiod的选取。
4、dom选择
* dom=document.forms['myForm'].myDropdown
* dom=document.images[56]
*
dom=function foo() { return document.links[1]; }; foo();
5、css选择器这个不常用,它可以支持css2,
css3选择器
* css=a[href="#id3"]
* css=span#firstChild + span
注:xpath和css定位方法使用在firefox中的XPath Checker和firebug插件很容易获取。
二、使用nose框架模块中的setup和tearDown实现只启动一次浏览器,只登录退出一次。
1.在pyuint基础上安装nose框架
2.在eclipse中安装pydev插件,工具栏Window
-Preferences-Pydev-Pyunit-Test Runner选择Nose test runner
3.然后python正常的单元测试的方法创建pydev moudle,使用模块编写测试用例,不是传统的uinttest编写用例的方法,eg:
# encoding=gbk
fromseleniumimportselenium
sel = selenium("localhost",4444,"*firefox","http://192.168.0.80:9003/")#设置浏览器为全局变量
defsetUp():#setUp方法中启动一次浏览器,登录一次
"""初始化登录"""
username="admin"
password="admin"
sel.start()
sel.open("/secure/login")
sel.type("username", username)
sel.type("password", password)
sel.click("signin")
deftearDown():#tearDown中退出登录关闭浏览器
"""退出注销"""
sel.open("/agentconfigs/show")
sel.wait_for_page_to_load("30000")
sel.click(u"link=[注销]")
sel.wait_for_page_to_load("30000")
sel.close()
deftest_channelAdd():
"""增加渠道"""
deftest_productAdd():
"""增加产品"""
。。。。。
三、使用selenium这个对象来进行测试
1 获取标: assertEquals("Insert title
here", selenium.getTitle());
2 判断页面是否存在一个user.email元素 assertTrue(selenium.isElementPresent("xpath=//input[@name='user.email']"));
3 得到文本框里的文字: assertEquals(selenium.getValue("xpath=//input[@name='user.username']"),"xxxaas");
4 测试check box assertTrue(selenium.isChecked("xpath=//input[(@name='user.sex')and(@value='男')]"));
5 点击提交按钮:
selenium.click("xpath=//input[@type='button']");
6 等待页面载入:
selenium.waitForPageToLoad("2000");
7 验证指定文本出现在提交给用户的页面上:
assertTrue(selenium.isTextPresent("验证码输入有误,请核实后再输入"));
8 判断下拉框里选择了哪个选项:assertEquals(selenium.getSelectedIndex("xpath=//SELECT[@name='HATIMING']"),
"1");
9 如何测试一些错误消息的显示?assertTrue(selenium.getBodyText().indexOf("错误消息")>=0);getBodyText返回的时浏览器页面上的文字,不回包含html代码的,如果要显示html代码,用下面这个:selenium.getHtmlSource();
四、“from
selenium import selenium ImportError: No module named selenium”解决方法
将\selenium-remote-control-1.0.1\selenium-python-client-driver-1.0.1下把selenium.py拷贝到\Python25\Lib目录
五、安装selenium ide 注意事项:安装的一定是selenium ide,而不是selinium ide button.