---
title: "selenium  元素定位"
author: "mailx8"
date: "2017-11-28T14:12:47Z"
tags: []
categories: ["编程语言"]
slug: "selenium"
draft: false
lastmod: "2017-11-28T14:12:47Z"
id: 2401115
url: "https://mailx8.iteye.com/blog/2401115"
---

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

searchBox.click();

 

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

 

3: List&lt;WebElement&gt; buttons = driver.findElements(By.tagName("button"));

 

4:List&lt;WebElement&gt; 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&gt;dl&gt;dt&gt;input\[id=’ J\_password’]"));

 

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

 

&lt;button id="J\_sidebar\_login" class="btn btn\_big btn\_submit" type="submit"&gt;登录&lt;/button&gt;

 

 

 

cssSelector引用元素代码如下：

 

driver.findElement(By.cssSelector("button.btn.btn\_big.btn\_submit"))

 

 

[文档](http://www.douzhua.com)