- 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 - 獲取元素文字
我們可以在 Puppeteer 中獲取元素文字。這可以透過 textContent 屬性來實現。元素的此屬性作為引數傳遞給 getProperty 方法。
語法
獲取元素文字的語法如下:
const n = await page.$("#txt")
const t = await (await n.getProperty('textContent')).jsonValue()
在下圖中,讓我們獲取突出顯示元素的文字 - 關於 Tutorialspoint:
首先,請按照 Puppeteer 中“基本測試”章節中的步驟 1 到 2 操作,步驟如下:
步驟 1 - 在建立 node_modules 資料夾的目錄(Puppeteer 和 Puppeteer core 已安裝的位置)中建立一個新檔案。
Puppeteer 安裝的詳細資訊在“Puppeteer 安裝”章節中進行了討論。
右鍵單擊建立 node_modules 資料夾的資料夾,然後單擊“新建檔案”按鈕。
步驟 2 - 輸入檔名,例如 testcase1.js。
步驟 3 - 將以下程式碼新增到建立的 testcase1.js 檔案中。
//Puppeteer library
const pt= require('puppeteer')
async function getText(){
//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/about/about_careers.htm')
//identify element
const f = await page.$("[class='heading']")
//obtain text
const text = await (await f.getProperty('textContent')).jsonValue()
console.log("Text is: " + text)
}
getText()
步驟 4 - 使用以下命令執行程式碼:
node <filename>
因此,在我們的示例中,我們將執行以下命令:
node testcase1.js
命令成功執行後,元素 - 關於 Tutorialspoint 的文字將列印到控制檯。
廣告