辅助工具:

chrome浏览器,F12打开控制台;

Firefox浏览器,F12打开控制台;

或者选中要定位的元素右键

安装firefox扩展firebug和firepath;

安装之后F12可调用firebug;

firepath内嵌在firebug中;

选中要定位的页面元素,右键可以获得该元素的xpath和css路径,方便使用xpaht和css方式定位元素,在firepath中可以自己输入xpath表达式和css表达式来定位元素。

1.通过ID定位

public static By id(String id)
Parameters:
id - The value of the "id" attribute to search for
Returns:
a By which locates elements by the value of the "id" attribute.

之前例子中用到的:

WebElement searchButton = driver.findElement(By.id("stb"));

就可以获取到该元素.

 

2.通过name定位

public static By name(String name)
Parameters:
name - The value of the "name" attribute to search for
Returns:
a By which locates elements by the value of the "name" attribute.

之前例子中用到的:

WebElement searchInput = driver.findElement(By.name("query"));

就可以获取到该元素.

 

3.通过xpath定位

public static By xpath(String xpathExpression)
Parameters:
xpathExpression - The xpath to use
Returns:
a By which locates elements via XPath

通过firebug右键要定位的元素,已百度搜索button为例:

<input id="search-submit" class="btn-engine" type="submit" value="搜 索"/>

得到的xpath:.//*[@id='search-submit']

可以写成:

WebElement element = driver.findElement(By.xpath("//*[@id='search-submit']"))

 

4.通过cssSelector定位

public static By cssSelector(String selector)
Finds elements via the driver's underlying W3 Selector engine. If the browser does not implement the Selector API, a best effort is made to emulate the API. In this case, we strive for at least CSS2 support, but offer no guarantees.
Parameters:
selector - css expression
Returns:
a By which locates elements by CSS.

通过firebug右键要定位的元素

 

5.通过classname定位

public static By className(String className)
Finds elements based on the value of the "class" attribute. If an element has many classes then this will match against each of them. For example if the value is "one two onone", then the following "className"s will match: "one" and "two"
Parameters:
className - The value of the "class" attribute to search for
Returns:
a By which locates elements by the value of the "class" attribute.

<input id="search-submit" class="btn-engine" type="submit" value="搜 索"/>

使用classname定位的方式就为:By.className("btn-engine")

WebElement element = driver.findElement(By.className("btn-engine"));

 

6.通过linktext定位

public static By linkText(String linkText)Parameters:

linkText - The exact text to match against

Returns:

a By which locates A elements by the exact text it displays
<a class="mnav" name="tj_trnuomi" href="http://www.nuomi.com/?cid=002540">糯米</a>

使用linktext定位的方式就为:

WebElement element = driver.findElement(By.linkText("糯米"));

 

7.通过partialLinkText定位

public static By partialLinkText(String linkText)
Parameters:
linkText - The text to match against
Returns:
a By which locates A elements that contain the given link text

类似linktext的方法,通过给出的链接文本去定位,这个链接文本只要包含在整个文本中即可,可理解为模糊匹配。

 

8.通过jQuery来定位元素

在使用selenium调用jQuery查找元素之前你需要确认你要测试的页面时候使用了jQuery, 如果使用了jQuery则直接使用find方法查找元素;如果你的测试页面没有使用到jQuery,则需要对当前页面注入jQuery库。

打开控制台输入jQuery如果返回function(e, t),则说明该页面引用了jQuery,如果报错则说明没有引用jQuery。

以百度首页上的菜单为例子:

WebDriver driver = new FirefoxDriver();
driver.mange().window().maximize();
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
driver.get("https://www.baidu.com");
List<WebElement> webElements = jsExecutor.exe cuteScript("return jQuery.find('a.mnav')");
Assert.assertEquals(webElements.size(),6);
Assert.assertEquals(webElements.get(2).getText(), "hao123");

上诉代码使用了jQuery的find方法来查找元素。找到符合"a.mnav" 的元素,然后通过JavascriptExecutor执行jQuery命令。你也可以通过firefox浏览器的控制台输入jQuery.find('a.mnav')或者$.find('a.mnav')按下回车键之后就可以返回你要查找的元素。

未加载jQuery库页面定位:

对未使用jQuery的页面,可以再加载页面的时候对这个页面注入jQuery的支持库。所以在打开页面的时候先要判断该页面是否使用的jQuery,如果没有就执行一段注入jQuery的代码,然后在使用jQuery的find方法即可。

以一个没有加载jQuery的网站http://www.2345.com/为例,通过控制台依次输入一下js可以达到注入的目的:

var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/Javascript';
newScript.src = "http://code.jquery.com/jquery-2.1.4.min.js";
headID.appendChild(newScript);

返回:<script type="text/Javascript" src="http://code.jquery.com/jquery-2.1.4.min.js">这段代码就证明已经注入成功,为了确保注入成功,再次在控制台输入界面输入jQuery,返回function(a, b)就说明注入成功。

在控制台输入命令:"$find('input.sch_btn')"来查找到这个“搜索一下”按钮

完整代码如下:

import java.util.List;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
public class TestNotLoadJquery {
public static void main(String[] args) {
Webdriver driver = new FirefoxDriver();
driver.manage().window().maximize();
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
driver.get("http://www.2345.com/");
if(!jQueryLoaded(jsExecutor)) {
//如果检测到没有jQuery库就执行注入操作
inJectquery(jsExecutor);
}
//找到搜索一下按钮元素
List<WebElement> searchButoon = (List<WebElement>) jsExecutor.exe cuteScript("return jQuery.find('input.sch_btn')");
//验证按钮的文本
Assert.assertEquals(searchButton.get(0).getAttribute("value"), "搜索一下")
driver.quit();
} /**注入jQuery支持**/
public static void inJectquery(JavascriptExecutor jsExecutor){ jsExecutor.executeScript("var headID = document.getElementsByTagName(\"head\")[0];"
+ "var newScript = document.createElement('script');"
+ "newScript.type = 'text/Javascript';"
+ "newScript.src=\"http://code.jquery.com/jquery-2.1.4.min.js\";"
+ "headID.appendChild(newScript);"); } /**判断当前页面是否使用了jQuery**/
public static Boolean jQueryLoaded(JavascriptExecutor jsExecutor) { Boolean laoded = true; try{
loaded = (Boolean) jsExecutor.executeScript("return jQuery()! = null");
}catch(WebDriverException e){
loaded = false;
}
return loaded;
}
}

Selenium2(java)定位页面元素 二的更多相关文章

  1. Java+selenium之WebDriver定位页面元素(二)

    Selenium-Webdriver 提供了强大的元素定位方法,支持以下三种方法: 单个对象的定位方法,多个对象的定位方法和层级定位 1. 定位单个元素 // 对于元素的属性包含 id 的情况适用,推 ...

  2. selenium第三课(selenium八种定位页面元素方法)

    selenium webdriver进行元素定位时,通过seleniumAPI官方介绍,获取页面元素的方式一共有以下八种方式,现按照常用→不常用的顺序分别介绍一下. 官方api地址:https://s ...

  3. 定位页面元素之xpath详解以及定位不到测试元素的常见问题

    一.定位元素的方法 id:首选的识别属性,W3C标准推荐为页面每一个元素设置一个独一无二的ID属性, 如果没有且很难找到唯一属性,解决方法:(1)找开发把id或者name加上.如果不行,解决思路可以是 ...

  4. selenium webdriver学习(四)------------定位页面元素(转)

    selenium webdriver学习(四)------------定位页面元素 博客分类: Selenium-webdriver seleniumwebdriver定位页面元素findElemen ...

  5. selenium定位页面元素的一件趣事

    PS:本博客selenium分类不会记载selenium打开浏览器,定位元素,操作页面元素,切换到iframe,处理alter.confirm和prompt对话框这些在网上随处可见的信息:本博客此分类 ...

  6. 使用CSS选择器定位页面元素

    摘录:http://blog.csdn.net/defectfinder/article/details/51734690 CSS选择器也是一个非常好用的定位元素的方法,甚至比Xpath强大.在自动化 ...

  7. Selenium 定位页面元素 以及总结页面常见的元素 以及总结用户常见的操作

    1. Selenium常见的定位页面元素 2.页面常见的元素 3. 用户常见的操作 1. Selenium常见的定位页面元素 driver.findElement(By.id());driver.fi ...

  8. webdriver定位页面元素时使用set_page_load_time()和JavaScript停止页面加载

    webdriver定位页面元素时使用set_page_load_time()和JavaScript停止页面加载 原文:https://my.oschina.net/u/2344787/blog/400 ...

  9. 关于appium操作真机打开app之后无法定位页面元素的问题的解决办法

    appium操作真机打开app后无法定位页面元素:例如微信或者支付宝支付时,手机的安全控件会对支付环境进行保护,会断掉当前appium与真机的链接,导致连接失败,无法定位到页面元素,在做ui自动化之前 ...

随机推荐

  1. Tree of Life (easy)

    Tree of Life (easy) Heidi has finally found the mythical Tree of Life – a legendary combinatorial st ...

  2. photoshop基础教程视频-贺叶铭-传智播客-笔记

    界面构成 1.菜单栏 2.工具箱 3.工具属性栏 4.悬浮面板 5.画布 ctrl+n 新建对话框 (新建画布) 画布200*200大小,是指以毫米为单位,当不说单位,默认是毫米. 打开对话框:ctr ...

  3. apache2.2.25+mod_jk-apache-2.2.2.so+apache-tomcat-7.0.56集群

    1.安装httpd-2.2.25-win32-x86-no_ssl.msi 按默认安装路径,我电脑如果自定义的话安装不了 2.下载mod_jk-apache-2.2.2.so 3.下载tomcat 我 ...

  4. 安卓布局修改基础常识篇之TextView属性

    [天使]安卓布局修改基础常识篇之TextView属性 在修改布局xml文件时需要熟练掌握一些属性,以下是TextView也就是文本的属性:android:autoLink 是否自动链接网址或邮箱地址: ...

  5. [转]读取assets目录下的数据库文件

    在做Android应用的时候,不可避免要用到数据库.但是当我们把应用的apk部署到真机上的时候,已经创建好的数据库及其里边的数据是不能随着apk一起安装到真机上的. (PS:这篇博客解决了我前面博客中 ...

  6. PAT (Advanced Level) 1005. Spell It Right (20)

    简单题. #include<iostream> #include<cstring> #include<cmath> #include<algorithm> ...

  7. sublime text 主题推荐

    Soda Spacegray Flatland Tomorrow Base 16 Solarized Predawn itg.flat 其他所有的配色方案和主题.

  8. SpringMVC 接收表单数据的方式 - Samuel - 博客频道 - CSDN.NET

    1.@RequestParam @RequestMapping(value = "/xxxx.do") public void create(@RequestParam(value ...

  9. SpringMVC轻松学习-SpringMVC介绍(一)

    Spring  MVC 背景介绍 Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块.使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 ...

  10. CodeForces 621A Wet Shark and Odd and Even

    水题 #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #inclu ...