如何使用没有id和名称的木偶师点击特定的TD元素



我在试图找到一种方法来点击导航菜单中的子菜单选项时遇到了问题我想点击的子菜单选项及其代码

有没有一种方法可以根据它的内容或其他选择来选择它?

我尝试了await page.click();,但由于我没有任何id、名称或值来识别该选项,它会自动关闭铬页面

还尝试点击内容const select = require('puppeteer-select'); const element = await select(page).getElement('div:contains(Negociação)'); await element.click();也不起作用。

可以通过文本过滤某些元素。下面是一个关于如何选择table元素并在其所有单元格中搜索给定文本的示例。

我首先编写了两个助手函数,用于从一个元素中获取文本,另一个用于在元素数组中搜索文本:

// 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()
}

使用给定的辅助函数,您现在可以选择表并在其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作为明文而不是图像提供。其他用户可以很容易地复制纯文本进行测试和调试。

欢迎留言。

最新更新