- Puppeteer 教程
- Puppeteer - 首頁
- Puppeteer - 簡介
- Puppeteer - 元素處理
- Puppeteer - Google 使用
- Puppeteer - NodeJS 安裝
- Puppeteer VS Code 配置
- Puppeteer - 安裝
- Puppeteer - 基本測試
- Puppeteer - 無頭模式執行
- Puppeteer 與 Selenium 的比較
- Puppeteer 與 Protractor 的比較
- Puppeteer 與 Cypress 的比較
- Puppeteer - 瀏覽器操作
- Puppeteer - 標籤頁處理
- Puppeteer - 基本命令
- Puppeteer - Firefox
- Puppeteer - Chrome
- Puppeteer - 處理確認警告框
- Puppeteer - 處理下拉選單
- Puppeteer - 定位器
- Puppeteer - XPath 函式
- Puppeteer - XPath 屬性
- Puppeteer - XPath 分組
- Puppeteer - 絕對 XPath
- Puppeteer - 相對 XPath
- Puppeteer - XPath 軸
- Puppeteer - 型別選擇器
- 名稱選擇器 & 類名選擇器
- Puppeteer - ID 選擇器
- Puppeteer - 屬性選擇器
- Puppeteer - 處理連結/按鈕
- 處理編輯框 & 複選框
- Puppeteer - 處理框架
- Puppeteer - 鍵盤模擬
- Puppeteer - 獲取元素文字
- Puppeteer - 獲取元素屬性
- Puppeteer - 裝置模擬
- Puppeteer - 停用 JavaScript
- Puppeteer - 同步
- Puppeteer - 擷取螢幕截圖
- Puppeteer 有用資源
- Puppeteer - 快速指南
- Puppeteer - 有用資源
- Puppeteer - 討論
Puppeteer - XPath 函式
為了唯一地確定一個元素,我們可以藉助 html 標籤中的任何屬性,或者使用 html 標籤上屬性的組合。大多數情況下使用 id 屬性,因為它在頁面中是唯一的。
但是,如果不存在 id 屬性,我們可以使用其他屬性,例如 class、name 等。如果不存在 id、name 和 class 等屬性,我們可以利用僅對該標籤可用的唯一屬性或屬性及其值的組合來識別元素。為此,我們必須使用 xpath 表示式。
如果元素存在重複的屬性或沒有屬性,則使用函式 text() 來識別元素。為了使用 text() 函式,該元素必須在頁面上顯示可見的文字。
語法
使用 text() 函式的語法如下:
//tagname[text()='visible text on element']
如果元素的值或文字部分是動態的或非常長,我們可以使用 contains() 函式。為了使用 contains() 函式,該元素必須具有屬性值或文字。
語法
使用 contains() 函式的語法如下:
//tagname[contains(@attribute,'value')] //tagname[contains(text(),'visible text on element')]
如果元素的文字以特定文字開頭,我們可以使用 starts-with() 函式。
語法
使用 starts-with() 函式的語法如下:
//tagname[starts-with(text(),'visible text on element')
在以上所有函式中,tagname 是可選的。我們可以使用符號 * 代替 tagname。
在下圖中,讓我們藉助其顯示的文字識別元素 - 圖書館,然後單擊它。
該元素的 xpath 將為 //*[text()='Library']。
這裡,我們使用 xpath 選擇器,因此必須使用方法:page.$x(xpath 值)。有關此方法的詳細資訊在章節 - Puppeteer 定位器中討論。
首先,請按照 Puppeteer 上基本測試章節中的步驟 1 到 2 操作,步驟如下:
步驟 1 - 在建立 node_modules 資料夾的目錄(Puppeteer 和 Puppeteer 核心已安裝的位置)中建立一個新檔案。
有關 Puppeteer 安裝的詳細資訊在 Puppeteer 安裝章節中討論。
右鍵單擊建立 node_modules 資料夾的資料夾,然後單擊“新建檔案”按鈕。
步驟 2 - 輸入檔名,例如 testcase1.js。
步驟 3 - 在建立的 testcase1.js 檔案中新增以下程式碼。
//Puppeteer library
const pt= require('puppeteer')
async function selectorFunTextXpath(){
//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 xpath function - text() then click
const b = (await page.$x("//*[text()='Library']"))[0]
b.click()
//wait for sometime
await page.waitForTimeout(4000)
//obtain URL after click
console.log(await page.url())
}
selectorFunTextXpath()
步驟 4 - 使用以下命令執行程式碼:
node <filename>
因此,在我們的示例中,我們將執行以下命令:
node testcase1.js
成功執行命令後,單擊元素“圖書館”後導航到的頁面的 URL - https://tutorialspoint.tw/tutorialslibrary.htm 將列印到控制檯中。