WebdriverIO - XPath 定位器



導航到網頁後,我們必須與頁面上可用的 Web 元素進行互動,例如單擊連結/按鈕、在編輯框中輸入文字等等,以完成我們的自動化測試用例。

為此,我們的首要任務是識別元素。我們可以為元素建立一個 XPath 用於識別它。下面討論建立 XPath 表示式的規則:

XPath 的語法是

//tagname[@attribute='value']

這裡,標籤名是可選的。

例如:

//img[@alt='tutorialspoint']

讓我們看看突出顯示的連結“首頁”的 HTML 程式碼。您的電腦上將出現以下螢幕:

Home

元素“首頁”的 XPath 如下:

//a[@title='TutorialsPoint - Home']. 

您的電腦上將出現以下螢幕:

Xpath

在 WebdriverIO 程式碼中,我們可以按以下格式指定元素的 XPath 表示式:

$('value of the xpath expression')

或者,我們可以將此表示式儲存在一個變數中:

const p = $('value of the xpath expression')

讓我們識別下圖中突出顯示的文字並獲取其文字:

Element

上面突出顯示的元素的 XPath 如下:

//li[@class='heading']

首先,請按照“使用 WebdriverIO 的正常流程”章節中的步驟 1 到 5 進行操作,步驟如下:

步驟 1 - 安裝 NodeJS。“使用 NodeJS 入門”章節詳細介紹瞭如何執行此安裝。

步驟 2 - 安裝 NPM。“NPM 安裝”章節詳細介紹瞭如何執行此安裝。

步驟 3 - 安裝 VS Code。“VS Code 安裝”章節詳細介紹瞭如何執行此安裝。

步驟 4 - 建立配置檔案。“配置檔案生成”章節詳細介紹瞭如何執行此安裝。

步驟 5 - 建立一個規範檔案。“Mocha 安裝”章節詳細介紹瞭如何執行此安裝。

步驟 6 - 將以下程式碼新增到建立的 Mocha 規範檔案中。

// test suite name
describe('Tutorialspoint application', function(){
   //test case
   it('Identify element with Xpath', function(){        
      // launch url
      browser.url('https://tutorialspoint.tw/about/about_careers.htm')
      //identify element with xpath then obtain text
      console.log($("//li[@class='heading']").getText() + " - is the text.")
   });
});

使用以下命令執行配置檔案 - wdio.conf.js 檔案:

npx wdio run wdio.conf.js. 

有關如何建立配置檔案的詳細資訊,請參閱“wdio.conf.js 檔案”章節和“配置檔案生成”章節

您的電腦上將出現以下螢幕:

File Generation

命令成功執行後,元素“關於 Tutorialspoint”的文字將列印在控制檯中。

包含文字的 XPath 定位器

導航到網頁後,我們必須與頁面上可用的 Web 元素進行互動,例如單擊連結/按鈕、在編輯框中輸入文字等等,以完成我們的自動化測試用例。

我們可以為元素建立一個 XPath 用於識別它。但是,在某些情況下,沒有可用的 HTML 屬性或標籤名來唯一標識元素。

在這種情況下,我們可以使用 text 函式,藉助頁面上可見的文字為元素建立 XPath。text 函式區分大小寫。

下面討論使用可見文字建立 XPath 表示式的規則:

XPath 的語法如下:

//tagname[text()='displayed text']. 

例如:

//li[text()='WebdriverIO']

讓我們使用 XPath 中的可見文字,識別下圖中突出顯示的元素:

Element Highlighted

使用 text() 函式,上面突出顯示的元素的 XPath 如下:

//li[text()='About Tutorialspoint'] 

首先,請按照“使用 WebdriverIO 的正常流程”章節中的步驟 1 到 5 進行操作,步驟如下:

步驟 1 - 安裝 NodeJS。“使用 NodeJS 入門”章節詳細介紹瞭如何執行此安裝。

步驟 2 - 安裝 NPM。“NPM 安裝”章節詳細介紹瞭如何執行此安裝。

步驟 3 - 安裝 VS Code。“VS Code 安裝”章節詳細介紹瞭如何執行此安裝。

步驟 4 - 建立配置檔案。“配置檔案生成”章節詳細介紹瞭如何執行此安裝。

步驟 5 - 建立一個規範檔案。“Mocha 安裝”章節詳細介紹瞭如何執行此安裝。

步驟 6 - 將以下程式碼新增到建立的 Mocha 規範檔案中。

// test suite name
describe('Tutorialspoint application', function(){
   //test case
   it('Identify element with Xpath - text()', function(){
      // launch url
      browser.url('https://tutorialspoint.tw/about/about_careers.htm')
      //identify element with xpath - visible text then obtain text
      console.log($("//li[text()='About Tutorialspoint']").getText() + " - is the text.")
   });
});

使用以下命令執行配置檔案 - wdio.conf.js 檔案:

npx wdio run wdio.conf.js. 

有關如何建立配置檔案的詳細資訊,請參閱“wdio.conf.js 檔案”章節和“配置檔案生成”章節。

您的電腦上將出現以下螢幕:

Run Configuration

命令成功執行後,元素“關於 Tutorialspoint”的文字將列印在控制檯中。

廣告
© . All rights reserved.