selenium 元素定位

1: WebElement searchBox = driver.findElement(By.name("btnK"));

searchBox.click();

2:WebElement searchBox = driver.findElement(By.id("gbqfba"));

3: List<WebElement> buttons = driver.findElements(By.tagName("button"));

4:List<WebElement> allInputs = driver.findElements(By.tagName("input"));

//只打印所有文本框的值

for(WebElement e: allInputs){

if (e.getAttribute(“type”).equals(“text”)){

System.out.println(e.getText().toString()); //打印出每个文本框里的值

}

}

5:WebElement searchBox = driver.findElement(By.className("buttonStyle"));

6:WebElement aboutLink = driver.findElement(By.linkText("About Google"));

7: WebElement aboutLink = driver.findElement(By.partialLinkText("About"));

8:下面是相对路径的引用写法:

查找页面根元素://

查找页面上所有的input元素://input

查找页面上第一个form元素内的直接子input元素(即只包括form元素的下一级input元素,使用绝对路径表示,单/号)://form[1]/input

查找页面上第一个form元素内的所有子input元素(只要在form元素内的input都算,不管还嵌套了多少个其他标签,使用相对路径表示,双//号)://form[1]//input

查找页面上第一个form元素://form[1]

查找页面上id为loginForm的form元素://form[@id='loginForm']

查找页面上具有name属性为username的input元素://input[@name='username']

查找页面上id为loginForm的form元素下的第一个input元素://form[@id='loginForm']/input[1]

查找页面具有name属性为contiune并且type属性为button的input元素://input[@name='continue'][@type='button']

查找页面上id为loginForm的form元素下第4个input元素://form[@id='loginForm']/input[4]

1 driver.findElement(By.xpath(“//a[contains(@href, ‘logout’)]”));

1 driver.findElement(By.xpath(“//a[starts-with(@rel, ‘nofo’)]));

1 driver.findElement(By.xpath(“//*[text()=’退出’]));

1 driver.findElement(By.xpath(“//a[contains(text(), ’退出’)]));

8: 

WebElement password = driver.findElement(By.cssSelector("#J_login_form>dl>dt>input[id=’ J_password’]"));

cssSelector还有一个用处是定位使用了复合样式表的元素,之前在第4种方式className里面提到过。现在我们就来看看如何通过cssSelector来引用到第4种方式中提到的那个button。button代码如下:

<button id="J_sidebar_login" class="btn btn_big btn_submit" type="submit">登录</button>

cssSelector引用元素代码如下:

driver.findElement(By.cssSelector("button.btn.btn_big.btn_submit"))

文档

猜你喜欢

转载自mailx8.iteye.com/blog/2401115