[英]How to click on a specific TD element with puppeteer without id and name
我在嘗試找到一種方法來單擊此導航菜單中的子菜單選項時遇到問題我想單擊的子菜單選項及其代碼
有沒有辦法通過它的內容或其他選擇來選擇它?
我試過await page.click();
但由於我沒有任何標識、名稱或值來識別該選項,它會自動關閉 chromium 頁面
還嘗試點擊內容const select = require('puppeteer-select'); const element = await select(page).getElement('div:contains(Negociação)'); await element.click();
const select = require('puppeteer-select'); const element = await select(page).getElement('div:contains(Negociação)'); await element.click();
也沒有用。
可以通過文本過濾某些元素。 下面是一個關於如何 select table
元素並在其所有單元格中搜索給定文本的示例。
我首先編寫了 2 個輔助函數,用於從元素中獲取文本,另一個用於在元素數組中搜索文本:
// returns text for an array of elements
async function findElementByText(elements, searchText) {
for(let el of elements) {
// get the text of the element and return
// element if text matches
const text = await getText(el)
console.log(`found text: "${text}", searchText: "${searchText}"`)
// alternatively you could use this for being a little more error tolerant
// depends on your use case and comes with some pitfalls.
// return text.toUpperCase().includes(searchText.toUpperCase())
// compare text and return element if matched
if(searchText === text) {
return el
}
}
// NO element found..
console.log('No element found by text', searchText)
return null
}
// returns text from a html element
async function getText(element) {
const textElement = await element.getProperty('textContent')
const text = await textElement.jsonValue()
// make sure to remove white spaces.
return text.trim()
}
使用給定的輔助函數,您現在可以 select 表格並在其td
元素(單元格)中進行搜索。
// This selects the first found table. You may wanna grab the correct table by a classname.
const table = await page.$('table')
// select all cells in the table.
const cells = await table.$$('td')
// search in the cells for a given text. "cell" will be a JSHandle
// which can be clicked!
const searchText = 'text4'
const cell = await findElementByText(cells, searchText)
if(!cell) {
throw 'Cell with text ' + searchText + ' not found!!.'
}
console.log('clicking cell now.')
// click the element
await cell.click()
如果您自己托管 html,通過為您想要單擊的單元格設置類名或 ID 可以讓生活更輕松。 (僅在允許且可能的情況下)。
在你的下一個問題中,你應該提供 html 作為純文本而不是圖像。 純文本可以很容易地被其他用戶復制以進行測試和調試。
歡迎發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.