Selenium允許匹配部分字串以定位特定的Web元素。有三種機制可以使用CSS Selector完成字串的匹配。
- 匹配首碼
- 匹配尾碼
- 匹配子字串
下麵通過一個例子詳細介紹每種機制。在開始之前,請準備以下示例代碼(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" class="form-control" id="username" placeholder="UserName"/>
<input name="password" type="password" class="form-control" id="password" placeholder="Password"/>
<input name="continue" type="submit" id="continue" class="btn" value="登錄" />
</form>
</div>
</body>
<html>
1.匹配首碼
它允許使用匹配的首碼訪問特定的字串。
語法 :css = <HTML tag> <[attribute ^= string的首碼]>
^
- 使用首碼匹配字串的符號表示法。Suffix of the string
- 基於執行匹配操作的字串。
例如,上面本地的登錄頁面的“密碼”文本框定義CSS選擇器:css=input#password[name^='pass']
單擊“在頁面中查找目標”按鈕,檢查定義的CSS選擇器是否找到所需的元素。
2. 匹配尾碼
它允許使用匹配的尾碼訪問特定的字串。
語法:css = <HTML tag> <[attribute $=string的尾碼]>
$
- 使用尾碼匹配字串的符號表示法。
字串的尾碼 - 基於執行匹配操作的字串。
例如,上面本地的登錄頁面的“密碼”文本框定義CSS選擇器:css=input#password[name$='ord']
單擊“在頁面中查找目標”按鈕,檢查定義的CSS選擇器是否找到所需的元素。
3. 匹配子字串
它允許使用匹配的子字串訪問特定的字串。
語法:css = <HTML tag> <[attribute * = sub string]>
*
- 使用子字串匹配字串的符號表示法。sub string
- 基於其執行匹配操作的字串。
例如,上面本地的登錄頁面的“密碼”文本框定義CSS選擇器:css=input#password[name*='word']
單擊“在頁面中查找目標”按鈕,檢查定義的CSS選擇器是否找到所需的元素。
上一篇:
Selenium IDE定位策略
下一篇:
Selenium WebDriver簡介