如何使用Puppeteer检查特定元素(不是页面)上是否存在文本



我想在一个特定的元素上运行$x,而不是整个页面,并尝试了这个:

let selector = await page.$('.myClass"]');
let [el] = await selector.$x(`//p[contains(text(), 'myTextString')]`);
pass = el ? true : false

我期望传递值为false,因为myClass元素不包含myTextString,但el不是假的,因为myTextString存在于页面的其他地方。

是否有一种方法来检查特定元素上的文本字符串?

$x重新创建问题的代码:

const puppeteer = require('puppeteer');
async function test() {
const browser = await puppeteer.launch({ 
headless: false,
defaultViewport: null,
args: ['--start-maximized'] 
});
const page = await browser.newPage();
await page.goto('https://stackoverflow.com/');
//  select a header div with no text content
let selector = await page.$('#notify-container');
//  an element is still found, even though I'm running $x on the selector, not the page
let [el] = await selector.$x(`//h2[contains(text(), 'Find the best answer to your technical question, help others answer theirs')]`);
console.log(el);
await browser.close();
}
test();

根据文档,"该方法计算相对于elementHandle的XPath表达式作为其上下文节点"。因此,您只需要在XPath开头使用上下文节点符号:.//h2而不是//h2

最新更新