XPath是一种用于在XML文档中定位节点的语言。
当没有适合要查找的元素的id
或name
属性时,可以使用XPath作为替代。
XPath提供了以下定位策略:
- XPath绝对
- XPath属性
XPath绝对(不推荐)
XPath Absolute使用户能够提及从根HTML标记到特定元素的完整XPath位置。
建议不要这样做,因为它需要完整的XPath位置,如果Web元素的位置发生更改或者属于其他父级,则XPath将无法找到所需的元素。
语法://html/body/tag1[index]/tag2[index]/.../tagN[index]
示例://html/body/div[2]/div/div[2]/div/div/div/fieldset/form/div[1]/input[1]
XPath属性
如果没有适合要查找的元素的id
或name
属性,则始终建议使用XPath属性。
XPath属性允许使用不同的属性定位Web元素。
- 语法:
//htmltag[@attribute1='value1' and @attribute2='value2']
- 示例:
//input[@id='passwd' and @placeholder='password']
考虑一个关于如何在Selenium IDE中将XPath用作命令目标的示例。
我们将创建一个登录测试,以便可以更好地了解通过XPath定位元素。 因为,不建议使用XPath Absolute,因此使用XPath属性来定位Web元素。
- 启动Firefox浏览器。
- 单击浏览器右上角的Selenium图标。
- 它将启动Selenium IDE的默认界面。
- 单击“测试脚本编辑器”框中的命令文本框。
将第一个命令的属性修改为:
- 命令:
open
- 目标:
http://localhost
- 执行后,此命令将在Firefox浏览器上加载本地登录页面。
本地登录页面文件:index.php 的代码如下所示:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<title>Selenium示例™ - 许虎虎</title>
<body>
<div style="margin:auto;width:60%;">
<p>
Selenium示例
</p>
<?php
if($_POST){
$username = isset($_POST['username'])? trim($_POST['username']):'';
$password = isset($_POST['password'])? trim($_POST['password']):'';
if($username=='zaixian' && $password = '123456'){
echo "<p>您好,{$username} !</p>";
}
}
?>
<form id="loginForm" method="POST">
<input name="username" type="text" id="username"/>
<input name="password" type="password" id="password"/>
<input name="continue" type="submit" id="continue" value="登录" />
</form>
</div>
</body>
<html>
对于要输入的第二个命令,需要“用户名”文本框的标识元素,这将帮助IDE识别目标位置。右键单击“用户名”文本框,然后选择“检查元素”。
它将启动一个窗口,其中包含开发“usename”文本框所涉及的所有特定代码。
因此,将“username”文本框的XPath属性写为://input[@id="username" and @name="username"]
将第二个命令的属性修改为:
命令:open
目标://input[@id="username" and @name="username"]
执行此命令后,将单击“用户名”文本框。
对于另外两个元素:密码 输入框和 登录 按钮,可以类似的方式填写命令。填写完成后的自动测试命令如下所示:
然后开始执行测试,得到结果如下: