您好,我正在检查页面上的某个元素是否可见。
首先我想说我知道这里的解决方案:
async function isVisible(page, selector) {
return await page.evaluate((selector) => {
var e = document.querySelector(selector);
if (e) {
var style = window.getComputedStyle(e);
return style && style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
}
else {
return false;
}
}, selector);
}
但是这不适用于 xPaths。
是否有解决方案可以使用 xPath 返回有关元素可见性的 true
或 false
?
我正在考虑这样的事情
async function isVisible(page, xPathSelector){}
//Returns true or false
await isVisible(page, "//button[type='button' and text() = 'Click Me']");
谢谢!
答案 0 :(得分:1)
我可以建议两种变体:自动可见性检查和手动检查。
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch(/* { headless: false, defaultViewport: null } */);
try {
const [page] = await browser.pages();
await page.goto('https://example.org/');
console.log(await isVisible1(page, '//p')); // true
console.log(await isVisible1(page, '//table')); // false
console.log(await isVisible2(page, '//p')); // true
console.log(await isVisible2(page, '//table')); // false
} catch(err) { console.error(err); } finally { await browser.close(); }
async function isVisible1(page, xPathSelector){
try {
await page.waitForXPath(xPathSelector, { visible: true, timeout: 1000 });
return true;
} catch {
return false;
}
}
async function isVisible2(page, xPathSelector){
const [element] = await page.$x(xPathSelector);
if (element === undefined) return false;
return await page.evaluate((e) => {
const style = window.getComputedStyle(e);
return style && style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
}, element);
}