CSS選擇器子串

2019-10-18 00:55:29

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=='yiibai' && $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選擇器是否找到所需的元素。