您好,我正在检查页面上的元素是否可见。
首先,我想说我知道这里的解决方案:
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']");
谢谢!
发布于 2021-01-17 19:52:21
我可以推荐两个变种:自动可见性检查和手动检查。
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);
}
https://stackoverflow.com/questions/65755380
复制相似问题