Puppeteer - 處理下拉選單



在使用 Puppeteer 自動化測試時,我們可以處理 UI 中的下拉選單。靜態下拉選單在 html 程式碼中使用 select 作為標籤名進行識別,其選項使用 option 作為標籤名。

Command has been Successfully

處理下拉選單的方法

處理靜態下拉選單的一些方法 -

select()

此方法用於從下拉選單中選擇一個選項。要選擇的選項的值作為引數傳遞給此方法。

語法

語法如下 -

const page = await browser.newPage()
   const f = await page.$('[name="selType"]')
await f.select("subject")

我們還可以從多選下拉選單中選擇多個選項。

語法

語法如下 -

await f.select("subject", "name")

要從下拉選單中獲取選定的值,我們必須使用 getProperty 方法並將值作為引數傳遞給此欄位。

const v = await (await n.getProperty("value")).jsonValue()
console.log(v)

type()

此方法用於從下拉選單中選擇一個選項。要選擇的選項的值作為引數傳遞給此方法。

語法

語法如下 -

const page = await browser.newPage()
   const f = await page.$('[name="selType"]')
await f.type("subject")

首先,按照 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 dropDownHandle(){
   //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/tutor_connect/index.php')
   //identify dropdown then select an option by value
   const f = await page.$('[name="selType"]')
   await f.select("subject")
   //wait for sometime
   await page.waitForTimeout(4000)
   //get value selected
   const v = await (await f.getProperty("value")).jsonValue()
   console.log(v)
}
dropDownHandle()

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

node <filename>

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

node testcase1.j
Terminal Command

命令成功執行後,下拉選單 - 主題中所選選項的值將列印到控制檯。

廣告

© . All rights reserved.