The pierce selector in Puppeteer

The pierce selector in Puppeteer is an experimental feature that allows you to query shadow DOM elements more easily. Traditional CSS selectors don't pierce through shadow roots because they encapsulate their content to prevent styles and scripts from leaking in or out. The pierce selector solves this by bypassing the shadow DOM boundary and directly selecting elements within shadow trees.


How to Use the Pierce Selector in Puppeteer

Here’s an example of how to use it effectively:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  // Navigate to a page with shadow DOM
  await page.goto('https://example.com');

  // Select an element inside a shadow DOM using the pierce selector
  const element = await page.$('pierce:#shadow-element-id');

  if (element) {
    console.log('Shadow element found!');
    await element.click();
  } else {
    console.log('Element not found.');
  }

  await browser.close();
})();

Explanation

  • pierce selector syntax:
    Use pierce: as a prefix before the CSS selector to search within the shadow DOM.

  • Why use pierce?
    Regular CSS selectors in Puppeteer can't directly access elements inside a shadow tree. Without pierce, you would need to manually traverse shadow roots, which can be cumbersome.


When to Use It?

  • Shadow DOM elements: If a website uses web components or encapsulated DOM structures, such as custom elements with shadow DOM.
  • Avoid manual traversal: Reduces the need for cumbersome JavaScript like element.shadowRoot.querySelector().

Alternative: Recursive Shadow DOM Search

If the pierce selector isn't available, you can manually access shadow DOM elements like this:

const shadowHost = await page.$('#host-element');
const shadowRoot = await shadowHost.evaluateHandle(el => el.shadowRoot);
const shadowElement = await shadowRoot.$('#shadow-element');

This is more verbose, but it achieves the same goal if pierce support is unavailable or experimental in your Puppeteer version【19†source】【20†source】.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

Sparse encoder

max_active_runs of Airflow

how to delete all issues on project in sentry, 센트리 이슈 삭제하기

Nginx Openssl 설정

difference between truncate and truncate_preserve in hbase

To monitor logs for a Kubernetes CronJob

Sort the distinct values by their count in descending order using the DataFrame API

Chromium 개발 환경 세팅, 크로미움 개발 준비하기

Bash script samples