Advanced CSS Selectors for Targeted Screenshots
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:
01/* Elements with exact attribute value */02[data-component="pricing-table"]0304/* Elements with attribute containing a value */05[aria-label*="product description"]0607/* Elements with attribute starting with a value */08[href^="https://docs"]0910/* Elements with attribute ending with a value */11[src$=".svg"]
Example API call:
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:
01/* Direct children */02.product-list > .featured-item0304/* Descendants */05.dashboard article.report0607/* Adjacent siblings */08.error-message + .help-text0910/* General siblings */11.form-input ~ .validation-message
Pseudo-classes
Target elements based on their state or position:
01/* First child element */02.gallery-item:first-child0304/* Last child element */05.gallery-item:last-child0607/* Specific position */08.search-result:nth-child(3)0910/* Every other element */11.table-row:nth-child(even)1213/* Elements containing specific text */14button:contains("Subscribe")
Real-world Selector Strategies
Capturing Specific UI Components
To capture a specific component like a pricing table:
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 element12 selectorPadding: 2013 })14});
Capturing Elements That Appear After Interaction
For elements that only appear after user interaction:
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 modal11 document.querySelector('.view-details-button').click();1213 // Wait for the modal to appear14 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:
01const selectors = [02 '.header-navigation',03 '.hero-section',04 '.feature-comparison',05 '.testimonials',06 '.pricing-table',07 '.faq-section'08];0910// Capture each section separately11const 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 });2425 const data = await response.json();26 return {27 section: selector.replace('.', ''),28 screenshotUrl: data.screenshotUrl29 };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:
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});1213const data = await response.json();14console.log(`Selector matches ${data.matchCount} elements`);
Pre-execution Scripts for Verification
Add verification code to confirm your selector works:
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 exists11 const element = document.querySelector('.my-target-element');12 if (!element) {13 console.error('Element not found!');14 // Add a visible error message to the page15 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:
- Be as specific as possible: More specific selectors are processed faster
- Avoid universal selectors: Selectors like
* > .item
are very slow - Limit the depth: Deep nesting like
.a .b .c .d .e
is inefficient - 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:
01// Test the same selector across different browsers02const browsers = ['chrome', 'firefox', 'safari'];0304const 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 });1819 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.
Ready to Get Started?
Get your API key now and start capturing screenshots in minutes.