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:
Usepierce:
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. Withoutpierce
, 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】.
댓글
댓글 쓰기