Puppeteer - XPath 分組



為了唯一地確定一個元素,我們可以藉助 html 標籤中的任何屬性,或者使用 html 標籤上屬性的組合。大多數情況下使用 id 屬性,因為它在頁面中是唯一的。

但是,如果不存在 id 屬性,我們可以使用其他屬性,例如 class、name 等。如果不存在 id、name、class 等屬性,我們可以利用僅該標籤可用的獨特屬性或屬性及其值的組合來識別元素。為此,我們必須使用 xpath 表示式。

透過利用索引從匹配元素的集合中獲取一個元素稱為組索引。如果 xpath 表示式識別多個元素,則可以使用組索引。

編寫組索引的格式是先寫 xpath 表示式,然後在其後跟著用 [] 括起來的索引號。它表示一個 xpath 陣列,索引從 1 開始。函式 last() 用於指向 xpath 陣列中的最後一個元素。

語法

使用函式 last() 的語法如下:

(/table/tbody/tr/td[1]/input)[last()]

語法

函式 position() 用於獲取 xpath 陣列中特定位置的元素。語法如下:

(/table/tbody/tr/td[1]/input)[position()=1]

上述 xpath 表示式將獲取所有匹配元素組中的第一個元素。

在下圖中,讓我們識別突出顯示的編輯框並在其中輸入一些文字。

因此,xpath 表示式將如下所示:

Online Education

在上面的例子中,表格中有兩列(由 td 標籤表示),它們的父標籤是 tr 標籤。輸入框位於第一列。

因此,xpath 表示式將如下所示:

//table/tbody/tr/td[1]/input

在這裡,我們使用 xpath 選擇器,因此必須使用方法:page.$x(xpath value)。此方法的詳細資訊在 Puppeteer 定位器一章中進行了討論。

首先,請按照 Puppeteer 基本測試一章中的步驟 1 到 2 操作,步驟如下:

步驟 1 - 在建立 node_modules 資料夾的目錄(Puppeteer 和 Puppeteer core 已安裝的位置)中建立一個新檔案。

Puppeteer 安裝的詳細資訊在 Puppeteer 安裝一章中進行了討論。

右鍵單擊建立 node_modules 資料夾的資料夾,然後單擊“新建檔案”按鈕。

Node Modules

步驟 2 - 輸入檔名,例如 testcase1.js。

Testcase1.JS

步驟 3 - 在建立的 testcase1.js 檔案中新增以下程式碼。

//Puppeteer library
const pt= require('puppeteer')
async function selectorGroupXpath(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://tutorialspoint.tw/index.htm')
   //identify element with group index xpath then enter text
   const f = (await page.$x("//table/tbody/tr/td[1]/input"))[0]
   f.type("Puppeteer")
   //wait for sometime
   await page.waitForTimeout(4000)
   //capture screenshot
   await page.screenshot({
      path: 'tutorialspoint.png'
   });
   //browser close
   await browser.close()
}
selectorGroupXpath()

步驟 4 - 使用以下命令執行程式碼:

node <filename>

因此,在我們的示例中,我們將執行以下命令:

node testcase1.js
Tutorialspoint Puppeteer

命令成功執行後,在頁面目錄中會建立一個名為 tutorialspoint.png 的新檔案。它包含在瀏覽器中啟動的頁面(帶有 Puppeteer 文字)的螢幕截圖。

廣告

© . All rights reserved.