【问题标题】:Puppeteer - Check if xPath element is visiblePuppeteer - 检查 xPath 元素是否可见
【发布时间】:2021-01-17 19:52:21
【问题描述】:

您好,我正在尝试检查页面上的元素是否可见。

首先我想说我知道这里的解决方案:

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 的元素可见性的 truefalse

我在想这样的事情

async function isVisible(page, xPathSelector){}

//Returns true or false
await isVisible(page, "//button[type='button' and text() = 'Click Me']");

谢谢!

【问题讨论】:

  • 你能对这个按钮更明确一点吗?这是页面上不存在的按钮然后appears?还是总是在页面上?页面上是否有多个按钮,但只有一个按钮有“点击我”?

标签: node.js xpath puppeteer


【解决方案1】:

我可以建议 2 个变体:自动可见性检查和手动检查。

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);
}

【讨论】:

  • 你是个天才。谢谢你!
猜你喜欢
  • 2018-05-22
  • 2017-01-01
  • 1970-01-01
  • 2019-09-26
  • 2021-02-19
  • 2012-07-08
  • 2013-11-09
  • 2017-04-25
  • 2022-01-07
相关资源
最近更新 更多