Return to Blog List
Advanced CSS Selectors for Targeted Screenshots
CSS

Advanced CSS Selectors for Targeted Screenshots

April 11, 2025
6 min read

One of the most powerful features of our Screenshot API is the ability to target specific elements using CSS selectors. This capability allows you to capture just the parts of a webpage that matter to your use case, rather than the entire page. In this guide, we'll explore advanced CSS selector techniques to help you create more focused and useful screenshots.

Beyond Basic Selectors

While simple selectors like #header or .product-card work for many cases, complex web applications often require more sophisticated targeting:

Attribute Selectors

Target elements based on their attributes:

css
01/* Elements with exact attribute value */
02[data-component="pricing-table"]
03
04/* Elements with attribute containing a value */
05[aria-label*="product description"]
06
07/* Elements with attribute starting with a value */
08[href^="https://docs"]
09
10/* Elements with attribute ending with a value */
11[src$=".svg"]

Example API call:

javascript
01fetch('https://api.screenshotapi.com/capture', {
02 method: 'POST',
03 headers: {
04 'Content-Type': 'application/json',
05 'Authorization': 'Bearer YOUR_API_KEY'
06 },
07 body: JSON.stringify({
08 url: 'https://example.com/products',
09 selector: '[data-component="pricing-table"]',
10 format: 'png'
11 })
12})

Combinators

Target elements based on their relationship to other elements:

css
01/* Direct children */
02.product-list > .featured-item
03
04/* Descendants */
05.dashboard article.report
06
07/* Adjacent siblings */
08.error-message + .help-text
09
10/* General siblings */
11.form-input ~ .validation-message

Pseudo-classes

Target elements based on their state or position:

css
01/* First child element */
02.gallery-item:first-child
03
04/* Last child element */
05.gallery-item:last-child
06
07/* Specific position */
08.search-result:nth-child(3)
09
10/* Every other element */
11.table-row:nth-child(even)
12
13/* Elements containing specific text */
14button:contains("Subscribe")

Real-world Selector Strategies

Capturing Specific UI Components

To capture a specific component like a pricing table:

javascript
01const response = await fetch('https://api.screenshotapi.com/capture', {
02 method: 'POST',
03 headers: {
04 'Content-Type': 'application/json',
05 'Authorization': 'Bearer YOUR_API_KEY'
06 },
07 body: JSON.stringify({
08 url: 'https://example.com/pricing',
09 selector: '.pricing-container .pricing-table',
10 format: 'png',
11 // Add padding around the selected element
12 selectorPadding: 20
13 })
14});

Capturing Elements That Appear After Interaction

For elements that only appear after user interaction:

javascript
01const response = await fetch('https://api.screenshotapi.com/capture', {
02 method: 'POST',
03 headers: {
04 'Content-Type': 'application/json',
05 'Authorization': 'Bearer YOUR_API_KEY'
06 },
07 body: JSON.stringify({
08 url: 'https://example.com/product',
09 executeBeforeScreenshot: `
10 // Click the button that opens a modal
11 document.querySelector('.view-details-button').click();
12
13 // Wait for the modal to appear
14 await new Promise(resolve => setTimeout(resolve, 1000));
15 `,
16 selector: '.product-detail-modal',
17 format: 'png'
18 })
19});

Capturing Multiple Elements

To capture multiple elements in separate screenshots:

javascript
01const selectors = [
02 '.header-navigation',
03 '.hero-section',
04 '.feature-comparison',
05 '.testimonials',
06 '.pricing-table',
07 '.faq-section'
08];
09
10// Capture each section separately
11const screenshots = await Promise.all(selectors.map(async (selector) => {
12 const response = await fetch('https://api.screenshotapi.com/capture', {
13 method: 'POST',
14 headers: {
15 'Content-Type': 'application/json',
16 'Authorization': 'Bearer YOUR_API_KEY'
17 },
18 body: JSON.stringify({
19 url: 'https://example.com',
20 selector,
21 format: 'png'
22 })
23 });
24
25 const data = await response.json();
26 return {
27 section: selector.replace('.', ''),
28 screenshotUrl: data.screenshotUrl
29 };
30}));

Debugging CSS Selectors

If your selector isn't working as expected, try these approaches:

Using the Test Endpoint

Our API provides a selector testing endpoint:

javascript
01const response = await fetch('https://api.screenshotapi.com/test-selector', {
02 method: 'POST',
03 headers: {
04 'Content-Type': 'application/json',
05 'Authorization': 'Bearer YOUR_API_KEY'
06 },
07 body: JSON.stringify({
08 url: 'https://example.com',
09 selector: '.complex > .selector:nth-child(2)'
10 })
11});
12
13const data = await response.json();
14console.log(`Selector matches ${data.matchCount} elements`);

Pre-execution Scripts for Verification

Add verification code to confirm your selector works:

javascript
01const response = await fetch('https://api.screenshotapi.com/capture', {
02 method: 'POST',
03 headers: {
04 'Content-Type': 'application/json',
05 'Authorization': 'Bearer YOUR_API_KEY'
06 },
07 body: JSON.stringify({
08 url: 'https://example.com',
09 executeBeforeScreenshot: `
10 // Check if selector exists
11 const element = document.querySelector('.my-target-element');
12 if (!element) {
13 console.error('Element not found!');
14 // Add a visible error message to the page
15 const errorMsg = document.createElement('div');
16 errorMsg.style.position = 'fixed';
17 errorMsg.style.top = '0';
18 errorMsg.style.left = '0';
19 errorMsg.style.background = 'red';
20 errorMsg.style.color = 'white';
21 errorMsg.style.padding = '10px';
22 errorMsg.style.zIndex = '9999';
23 errorMsg.textContent = 'Target element not found!';
24 document.body.appendChild(errorMsg);
25 }
26 `,
27 selector: '.my-target-element',
28 format: 'png'
29 })
30});

Performance Considerations

Complex selectors can impact performance. Consider these tips:

  1. Be as specific as possible: More specific selectors are processed faster
  2. Avoid universal selectors: Selectors like * > .item are very slow
  3. Limit the depth: Deep nesting like .a .b .c .d .e is inefficient
  4. Use IDs when possible: ID selectors like #header are the fastest

Browser Compatibility

Different browsers may interpret complex CSS selectors differently. Our Screenshot API uses modern browser engines, but if you're targeting very specific elements with complex selectors, consider testing across multiple browser options:

javascript
01// Test the same selector across different browsers
02const browsers = ['chrome', 'firefox', 'safari'];
03
04const results = await Promise.all(browsers.map(async (browser) => {
05 const response = await fetch('https://api.screenshotapi.com/capture', {
06 method: 'POST',
07 headers: {
08 'Content-Type': 'application/json',
09 'Authorization': 'Bearer YOUR_API_KEY'
10 },
11 body: JSON.stringify({
12 url: 'https://example.com',
13 selector: '.complex > .selector:nth-child(2)',
14 browser,
15 format: 'png'
16 })
17 });
18
19 return {
20 browser,
21 result: await response.json()
22 };
23}));

By mastering these advanced CSS selector techniques, you can create more focused, useful screenshots that capture exactly what you need from any webpage.

SelectorsAdvanced

Ready to Get Started?

Get your API key now and start capturing screenshots in minutes.