selenium技巧2

C 定位页面元素

selenium-webdriver提供了强大的元素定位方法,支持以下三种方法。

单个对象的定位方法

多个对象的定位方法

层级定位 

定位单个元素

在定位单个元素时,selenium-webdriver提示了如下一些方法对元素进行定位。

 

 By.className(className))    

 By.cssSelector(selector)       

 By.id(id)                     

 By.linkText(linkText)          

 By.name(name)             

 By.partialLinkText(linkText)

 By.tagName(name)       

 By.xpath(xpathExpression)  

 

注意:selenium-webdriver通过findElement()\findElements()等find方法调用"By"对象来定位和查询元素。By类只是提供查询的方式进行分类。findElement返回一个元素对象否则抛出异常,findElements返回符合条件的元素List,如果不存在符合条件的就返回一个空的list。

1.使用className进行定位

当所定位的元素具有class属性的时候我们可以通过classname来定位该元素。

下面的例子定位了51.com首页上class为"username"的li。

Java代码

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

 

import org.openqa.selenium.By;

 

public class ByClassName {

 

  

   public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();

       driver.get("http://www.51.com");

        WebElement element =driver.findElement(By.className("username"));

        System.out.println(element.getTagName());

 

    }

}

输出结果:

Java代码

 

Li

2.使用id属性定位

51.com首页的帐号输入框的html代码如下:

Java代码

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

 

在下面的例子中用id定位这个输入框,并输出其title,借此也可以验证代码是否工作正常。

 

Java代码

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

public class ByUserId {

 

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                  

                   WebElementelement = dr.findElement(By.id("passport_51_user"));

                   System.out.println(element.getAttribute("title"));

         }

 

}

 

输出结果:

 Java代码

 

用户名/彩虹号/邮箱

 

3.使用name属性定位

51.com首页的帐号输入框的html代码如下:

 

Java代码

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

 

使用name定位

 

Java代码

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

public class ByUserId {

 

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                  

         WebElemente = dr.findElement(By.name("passport_51_user"));                                      System.out.println(element.getAttribute("title"));

         }

 

}

 

输出结果:

 Java代码

 

用户名/彩虹号/邮箱

 

4.使用css属性定位

51.com首页的帐号输入框的html代码如下:

Java代码

 

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

 

使用css定位

Java代码

 

WebElement e1 =dr.findElement(By.cssSelector("#passport_51_user"));

 

5.使用XPATH定位

51.com首页的帐号输入框的html代码如下:

Java代码

 

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

 

通过xpath查找:

Java代码

 

WebElement element=driver.findElement(By.xpath("//input[@id=' passport_51_user ']"));

 

6.使用其他方式定位

在定位link元素的时候,可以使用link和link_text属性;

另外还可以使用tag_name属性定位任意元素;

7.定位多个元素

上面提到findElements()方法可以返回一个符合条件的元素List组。看下面例子。

Java代码

import java.io.File;

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

import org.openqa.selenium.firefox.FirefoxDriver;

 

public class FindElementsStudy {

 

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   WebDriver  driver = new FirefoxDriver();

                   driver.get("http://www.51.com");

                  

                   //定位到所有<input>标签的元素,然后输出他们的id

                   List<WebElement>element = driver.findElements(By.tagName("input"));

                   for(WebElement e : element){

                            System.out.println(e.getAttribute("id"));

                   }

                  

                   driver.quit();

         }

}

 

输出结果:

Java代码

 

passport_cookie_login

gourl

passport_login_from

passport_51_user

passport_51_password

passport_qq_login_2

btn_reg

passport_51_ishidden

passport_auto_login

 

上面的代码返回页面上所有input对象

8.层级定位

层级定位的思想是先定位父元素,然后再从父元素中精确定位出其我们需要选取的子元素。

层级定位一般的应用场景是无法直接定位到需要选取的元素,但是其父元素比较容易定位,通过定位父元素再遍历其子元素选择需要的目标元素,或者需要定位某个元素下所有的子元素。

下面的代码演示了如何使用层级定位class为"login"的div,然后再取得它下面的所有label,并打印出他们的文本

Java代码

 

import java.io.File;

importjava.util.List;

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

importorg.openqa.selenium.firefox.FirefoxDriver;

publicclass LayerLocator {

 

         /**

          * @author gongjf

          */

         public static void main(String[] args){

        

                   WebDriver  driver = new FirefoxDriver();

                   driver.get("http://www.51.com");

                  

                   //定位class为"login"的div,然后再取得它下面的所有label,并打印出他们的值

                   WebElement element =driver.findElement(By.className("login"));

                    List<WebElement> el =element.findElements(By.tagName("label"));

                    for(WebElement e : el)

                   System.out.println(e.getText());

        

         }       

}

输出结果:

Java代码

 

帐号:

密码:

隐身

 

 D  如何对页面元素进行操作

找到页面元素后,怎样对页面进行操作呢?我们可以根据不同的类型的元素来进行一一说明。

1.输入框(text field or textarea)

 找到输入框元素:

WebElement element =driver.findElement(By.id("passwd-id"));

在输入框中输入内容:

element.sendKeys(“test”);

将输入框清空:

element.clear();

获取输入框的文本内容:

element.getText();

 

2.下拉选择框(Select)

找到下拉选择框的元素:

Select select = newSelect(driver.findElement(By.id("select")));

 

选择对应的选择项:

select.selectByVisibleText(“mediaAgencyA”);

select.selectByValue(“MA_ID_001”);

 

不选择对应的选择项:

select.deselectAll();

select.deselectByValue(“MA_ID_001”);

select.deselectByVisibleText(“mediaAgencyA”);

或者获取选择项的值:

select.getAllSelectedOptions();

select.getFirstSelectedOption();

 

 

对下拉框进行操作时首先要定位到这个下拉框,new一个Selcet对象,然后对它进行操作 

3.单选项(Radio Button)

找到单选框元素:

WebElement bookMode =driver.findElement(By.id("BookMode"));

选择某个单选项:

bookMode.click();

清空某个单选项:

bookMode.clear();

判断某个单选项是否已经被选择:

bookMode.isSelected();

4.多选项(checkbox)

多选项的操作和单选的差不多:

WebElement checkbox=driver.findElement(By.id("myCheckbox."));

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

5.按钮(button)

找到按钮元素:

WebElement saveButton =driver.findElement(By.id("save"));

点击按钮:

saveButton.click();

判断按钮是否enable:

 

saveButton.isEnabled ();

6.左右选择框

也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。例如:

Select lang = new Select(driver.findElement(By.id("languages")));

lang.selectByVisibleText(“English”);

WebElement addLanguage=driver.findElement(By.id("addButton"));

addLanguage.click();

7.弹出对话框(Popup dialogs)

Alert alert = driver.switchTo().alert();

alert.accept();

alert.dismiss();

alert.getText();

 

后面有具体的例子解释~

8.表单(Form)

Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:

WebElement approve =driver.findElement(By.id("approve"));

approve.click();

approve.submit();//只适合于表单的提交

9.上传文件(Upload File)

上传文件的元素操作:

WebElement adFileUpload = driver.findElement(By.id("WAP-upload"));

String filePath ="C:\test\\uploadfile\\media_ads\\test.jpg";

adFileUpload.sendKeys(filePath);

10.拖拉(Drag andDrop)

WebElement element=driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

 

(new Actions(driver)).dragAndDrop(element,target).perform();

 

11.导航(Navigationand History)

打开一个新的页面:

 driver.navigate().to("http://www.example.com");

 

通过历史导航返回原页面:

driver.navigate().forward();

driver.navigate().back();

                                                                                                                                           

E  iframe的处理

有时候我们在定位一个页面元素的时候发现一直定位不了,反复检查自己写的定位器没有任何问题,代码也没有任何问题。这时你就要看一下这个页面元素是否在一个iframe中,这可能就是找不到的原因之一。如果你在一个default content中查找一个在iframe中的元素,那肯定是找不到的。反之你在一个iframe中查找另一个iframe元素或default content中的元素,那必然也定位不到。

selenium webdriver中提供了进入一个iframe的方法:

WebDriverorg.openqa.selenium.WebDriver.TargetLocator.frame(String nameOrId)

也提供了一个返回default content的方法:

WebDriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent()

这样使我们面对iframe时可以轻松应对。

以下面的html代码为例,我们看一下处现iframe。

 

Html代码

 

main.html

 

<html>

   <head>

       <title>FrameTest</title>

   </head>

   <body>

         <divid = "id1">this is a div!</div>

       <iframe. id = "frame" frameborder="0" scrolling="no"style="left:0;position:absolute;" src ="frame.html"></iframe>

   </body>

</html>

 

 

 

frame.html

 

<html>

   <head>

       <title>this is a frame!</title>

   </head>

   <body>

         <divid = "div1">this is a div,too!</div>

         <label>input:</label>

         <inputid = "input1"></input>

   </body>

</html>

 

 

Java代码

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

public class FameStudy {

 

        

         publicstatic void main(String[] args) {

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "\\Your\\Path\\to\\main.html";

                   dr.get(url);

 

                   //在defaultcontent定位id="id1"的div

                   dr.findElement(By.id("id1"));

                  

                   //此时,没有进入到id="frame"的frame中时,以下两句会报错

                   dr.findElement(By.id("div1"));//报错

                   dr.findElement(By.id("input1"));//报错

                  

                   //进入id="frame"的frame中,定位id="div1"的div和id="input1"的输入框。

                   dr.switchTo().frame("frame");        

                   dr.findElement(By.id("div1"));

                   dr.findElement(By.id("input1"));

                  

                   //此时,没有跳出frame,如果定位defaultcontent中的元素也会报错。

                   dr.findElement(By.id("id1"));//报错

                  

                   //跳出frame,进入defaultcontent;重新定位id="id1"的div

                   dr.switchTo().defaultContent();

                   dr.findElement(By.id("id1"));

         }

 

}

 

 

小结:

switch_to方法会new1个TargetLocator对象,使用该对象的frame方法可以将当前识别的”主体”移动到需要定位的frame上去。 

F如何得到弹出窗口

在selenium 1.X里面得到弹出窗口是一件比较麻烦的事,特别是新开窗口没有id、name的时候。在selenium webdriver中得到新开窗口相对简单的多,它无关新开窗口的id、name等属性。以下面的html为例:

 

 

Html代码

 

 

<span style="white-space: normal;background-color: #ffffff;">test.html</span>

 

 

<html>

 

   <head><title>Test Popup Window</title></head>

 

   <body>

 

       <a id = "51" href = "http://www.51.com/" target ="_blank">Let's go!</a>

 

   </body>

 

</html>

 

 

下面的代码演示了如何去得到弹出的新窗口

 

Java代码

 

import java.util.Iterator;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

public class PopupWindowTest {

 

 

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   Stringurl ="\\Your\\Path\\to\\main.html";

                   dr.get(url);       

                   dr.findElement(By.id("51")).click();

                   //得到当前窗口的句柄

                   StringcurrentWindow = dr.getWindowHandle();

                   //得到所有窗口的句柄

                   Set<String>handles = dr.getWindowHandles();

                   Iterator<String>it = handles.iterator();

                   while(it.hasNext()){

                            if(currentWindow== it.next())  continue;

                            dr.switchTo().window(it.next());

                           

                   }

         }

 

}

 

输出结果:

 

title,url = 51.com真人配对玩游戏,http://www.51.com/

 

小结:

 

捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。(

在上面的代码里,使用windowhandle方法来获取当前浏览器窗口的句柄,使用了windowhandles方法获取所有弹出的浏览器窗口的句柄,然后通过排除当前句柄的方法来得到新开窗口的句柄。

在获取新弹出窗口的句柄后,使用switchto.window(newwindow_handle)方法,将新窗口的句柄作为参数传入既可捕获到新窗口了。

如果想回到以前的窗口定位元素,那么再调用1次switchto.window方法,传入之前窗口的句柄既可达到目的。

G 如何处理alert、confirm、prompt对话框

alert、confirm、prompt这样的js对话框在selenium1.X时代也是难啃的骨头,常常要用autoit来帮助处理。

试用了一下selenium webdriver中处理这些对话框十分方便简洁

 

Html代码

 

Dialogs.html  

 

<html>

 

   <head>

 

       <title>Alert</title>

 

   </head>

 

   <body>

 

       <input id = "alert" value = "alert" type ="button" nclick = "alert('欢迎!请按确认继续!');"/>

        <input id = "confirm" value= "confirm" type = "button" nclick = "confirm('确定吗?');"/>

         <inputid = "prompt" value = "prompt" type = "button"onclick = "var name = prompt('请输入你的名字:','请输入

 

你的名字'); document.write(name) "/>

        

 

   </body>

 

</html>

 

 

 以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在prompt对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字。

 

selenium webdriver处理这些弹层的代码如下:

 

Java代码

 

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

public class DialogsStudy {

 

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Dialogs.html";//"/Your/Path/to/main.html"

                   dr.get(url);

                  

                   //点击第一个按钮,输出对话框上面的文字,然后叉掉

                   dr.findElement(By.id("alert")).click();

                   Alertalert = dr.switchTo().alert();

                   Stringtext = alert.getText();

                   System.out.println(text);

                   alert.dismiss();

                  

                   //点击第二个按钮,输出对话框上面的文字,然后点击确认

                   dr.findElement(By.id("confirm")).click();

                   Alertconfirm = dr.switchTo().alert();

                   Stringtext1 = confirm.getText();

                   System.out.println(text1);

                   confirm.accept();

                  

                   //点击第三个按钮,输入你的名字,然后点击确认,最后

                   dr.findElement(By.id("prompt")).click();

                   Alertprompt = dr.switchTo().alert();

                   Stringtext2 = prompt.getText();

                   System.out.println(text2);

                   prompt.sendKeys("jarvi");

                   prompt.accept();

                  

         }

 

}

 

 

小结:

 

从以上代码可以看出dr.switchTo().alert();这句可以得到alert\confirm\prompt对话框的对象,然后运用其方法对它进行操作。对话框操作的主要方法有:

 

getText()    得到它的文本值

accept()      相当于点击它的"确认"

dismiss()    相当于点击"取消"或者叉掉对话框

sendKeys()输入值,这个alert\confirm没有对话框就不能用了,不然会报错。




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
常用命令篇: 1. Open(url) url可以是相对的,也可以是绝对的 如绝对的url:open(http://www.taobao.com/) 相对的url:open("/search?q=’aa’"); 2. Click(locator) click可以单击一个链接,按钮或者单选框复选框等。 Click系列的有:click、clickAt、clickAndWait、clickAtAndWait clickAt(locator,coordstring): coordstring是需要单击的坐标 3. doubleClick(locator) 双击操作,用户与click一致 4. type(locator,value) 可以为指定位置输入指定值,也可以为单选框和复选框按钮赋值,value是选项的值而不是文本内容 5. typeKeys(locator,value) 模拟用户输入的行为,与type不同的是,type是强行赋值,而typeKeys是完全模拟用户操作,一个键一个键敲上去的。当输入框中原来就有值时,使用type会用新值替换旧值,而typeKeys则是在原来值上进行追加。如,原来值为aaa,现在要输入bbb,使用type则最终值为bbb,使用typeKeys则最终值为aaabbb. 6. focus(locator) 将焦点移动到指定的元素上,如果是一个可输入的元素,则将聚焦到输入框 7. select(locator,option) 选择下列框中的选项,option默认为标签label 如selenium.select (“size_select”,”label=small”),id=size_select 8. selenium.goBack()后退 9. highlight(locator)指定元素高亮 10. refresh()刷新当前页面 11. AssertText(locator,pattern) 验证某个元素的文本值是否与预期值一致,locator为元素定位,pattern为预期值 12. AssertAttribute(attributelocator,pattern) 验证某个元素的某个属性值与预期值是否一致,attributelocator为属性定位,pattern为预期值 13.assertEquals(value,selenium.getAttribute(xpath+"@value")) 验证某个元素的属性值或者是文本值是否与预期值一致 14. assertInPara(remark_para_1, getRemark(engine_type)); 一般用于验证url和remark串 15. mouseOver(locator) 将鼠标停留在某个元素上,locator为元素定位。 16. mouseDown(locator)/mouseUp(locator) 用户在某个元素上按下或者释放鼠标。Locator为元素定位 17. keyDown(locator,keysequence)/ keyUp(locator,keysequence) 用户按下或者释放某一个按钮,Locator为元素定位,keysequence为按键对应的ASCII码 18. indexOf:判断两个字符串是否存在包含关系 若x=”abcd”;y=”bc”;则有X.indexOf(y)==0 若不存在包含关系,则X.indexOf(y)==-1 19. System.out.println(value); 可以向屏幕打印出value值,这个value值可以是元素的属性值或者文本值等 20. selenium.getCookie(); 可以取到当前页面的cookie值 21. selenium.deleteCookie(name,path) 删除cookie值中的某个参数,如下: selenium.deleteCookie("_nk_","path=/, domain=.taobao.com, recurse=true"); 删除_nk_参数,path的格式必须指定上面三个字段,path=/表示当前路径,domain=.taobao.com为改cookie所属的域,recurse=true 22. assertValue(locator,pattern) 验证某个可输入元素是否被赋了某个值 23. selenium.close() 关闭浏览器。 24. contextMenu(locator)打开关联的菜单,与右键作用差不多,但是对弹出的菜单selen

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值