Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use page.getByRole('button') when “button” means any control exposed to users and assistive technology. Use page.locator('button') when you specifically need native HTML <button> elements. In both cases, call evaluateAll() to turn the matched DOM nodes into ordinary JavaScript data containing text, labels, titles, types and disabled state.

Choose what “button” means

Google interfaces contain native buttons and custom controls that may expose an accessible button role. Those are not interchangeable inventories.

Accessible buttons

This locator follows the page’s accessibility tree. It can match a native <button> and a custom element whose semantics are exposed as role="button". It is the right starting point when your script represents what a keyboard user or screen-reader user can operate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Native HTML buttons

page.locator('button') selects only elements with the button tag. It will not include a clickable div, link, or custom widget that behaves like a button.

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Google’s live markup varies by product surface, locale, viewport, consent state and signed-in session. Therefore, do not assume that a named control or a particular class name exists everywhere. Define the exact page and state you need before writing an extractor.

Complete extraction script

The following Playwright script opens a page, waits for a stable state, and extracts both semantic and native inventories. Save it as extract-buttons.js.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage({
    viewport: { width: 1440, height: 1000 },
    locale: 'en-US'
  });

  await page.goto('https://www.google.com/', { waitUntil: 'domcontentloaded' });
  await page.waitForLoadState('networkidle').catch(() => {});

  const accessibleButtons = page.getByRole('button');
  const accessibleButtonData = await accessibleButtons.evaluateAll(buttons =>
    buttons.map(button => ({
      tag: button.tagName.toLowerCase(),
      text: button.textContent?.trim() ?? '',
      ariaLabel: button.getAttribute('aria-label'),
      title: button.getAttribute('title'),
      type: button.getAttribute('type'),
      disabled: button.hasAttribute('disabled')
    }))
  );

  const nativeButtons = await page.locator('button').evaluateAll(buttons =>
    buttons.map(button => ({
      text: button.textContent?.trim() ?? '',
      ariaLabel: button.getAttribute('aria-label'),
      title: button.getAttribute('title')
    }))
  );

  console.log(JSON.stringify({ accessibleButtonData, nativeButtons }, null, 2));
  await browser.close();
})();

evaluateAll() executes its callback in the browser context. The callback receives the elements currently matched by the locator and can use normal DOM APIs. The returned objects are serialized back to Node.js, so they are safe to write as JSON.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install and run it

  1. Install a current Node.js release.
  2. Create a directory, then run npm init -y.
  3. Install Playwright with npm install -D playwright.
  4. Download the browser binary with npx playwright install chromium.
  5. Run node extract-buttons.js.

The output contains one array for semantic button controls and another for native tags. Empty strings are used when a control has no text content; null is preserved for missing attributes.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Collect only visible native buttons

Visibility is a separate question from semantics. A native button query can include hidden template elements, off-screen controls, or elements hidden by CSS. Add the :visible filter when the inventory should represent currently visible native tags.

const visibleNativeButtons = await page.locator('button:visible').evaluateAll(buttons =>
  buttons.map(button => ({
    text: button.textContent?.trim() ?? '',
    ariaLabel: button.getAttribute('aria-label'),
    title: button.getAttribute('title')
  }))
);
console.log(visibleNativeButtons);

button:visible is not equivalent to getByRole('button'). The first is a CSS tag query with a visibility filter; the second is an accessibility-oriented query and may include custom controls.

Extract one specific Google control

For an action or a single known target, narrow the role locator with its accessible name rather than selecting a broad collection.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const searchButton = page.getByRole('button', { name: 'Search' });
await searchButton.waitFor();
const searchButtonData = await searchButton.evaluate(button => ({
  tag: button.tagName.toLowerCase(),
  text: button.textContent?.trim() ?? '',
  ariaLabel: button.getAttribute('aria-label'),
  title: button.getAttribute('title'),
  disabled: button.hasAttribute('disabled')
}));
console.log(searchButtonData);

Role locators are strict for single-target operations: if several controls have the same accessible name, Playwright reports an ambiguity instead of silently choosing one. Resolve that ambiguity by scoping to a container, refining the name, or deliberately using a collection operation such as count() or evaluateAll().

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
const resultRegion = page.locator('[role="main"]');
const buttonsInRegion = await resultRegion.getByRole('button').evaluateAll(buttons =>
  buttons.map(button => ({
    text: button.textContent?.trim() ?? '',
    ariaLabel: button.getAttribute('aria-label')
  }))
);

Wait for Google’s dynamic state

Locators resolve against the page when used, which helps when the interface re-renders. Your inventory is still only a snapshot. Collect it after the state that matters has appeared: after navigation, after opening a menu, after dismissing consent, or after results load.

Wait for a known control

await page.getByRole('button', { name: 'More' }).waitFor();
const menuButtons = await page.getByRole('button').evaluateAll(buttons =>
  buttons.map(button => button.textContent?.trim() ?? '')
);

Wait for a page signal

await page.waitForSelector('[role="main"]');
await page.waitForLoadState('networkidle').catch(() => {});

Network idle is not a universal guarantee on pages with analytics, streams, or long-lived connections. Prefer a meaningful selector or application-specific state when one is available.

Avoid premature locator.all()

locator.all() does not wait for matches and can be unpredictable while a list changes. For a complete inventory, wait first and use evaluateAll() at the intended state. If the page continues adding controls, take a second snapshot or wait for a stable application signal.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use resilient selectors, not Google’s internal classes

Playwright recommends prioritizing user-facing attributes and explicit contracts such as getByRole(). A role plus accessible name expresses intent and is usually more durable than a selector based on generated class names or a deep DOM path.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
  • Preferred: page.getByRole('button', { name: 'Settings' }) for a specific user-facing control.
  • Use when required: page.locator('button') when the requirement is literally native tags.
  • Last resort: CSS or XPath tied to implementation details, especially Google class names that can change without notice.

Codegen can provide a starting locator: open the target URL, run Playwright codegen, interact with the control, and review the generated role, text or test-id locator. Treat generated code as a draft; confirm that it matches your extraction definition and does not depend on accidental structure.

Shadow DOM and selector boundaries

Playwright locators cross open shadow roots by default. XPath does not pierce shadow roots, and closed-mode roots are not supported. If a custom Google surface renders a control in an open shadow root, a role locator may still find it; an XPath expression may not. For closed roots, extract only what the page exposes outside that boundary or use the component’s supported interface.

Extract richer attributes and state

Extend the mapping when your downstream process needs form behavior or accessibility metadata.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const data = await page.getByRole('button').evaluateAll(buttons =>
  buttons.map(button => ({
    tag: button.tagName.toLowerCase(),
    text: button.textContent?.trim() ?? '',
    ariaLabel: button.getAttribute('aria-label'),
    ariaPressed: button.getAttribute('aria-pressed'),
    ariaExpanded: button.getAttribute('aria-expanded'),
    title: button.getAttribute('title'),
    type: button.getAttribute('type'),
    disabled: button.hasAttribute('disabled'),
    hidden: button.hidden,
    className: button.className
  }))
);

Use textContent for raw descendant text. It may include text from visually hidden descendants. If you need a rendered label, compare it with the accessible name used by the role locator rather than assuming the two strings are identical.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and fixes

No buttons are returned

  • Cause: the page has not reached the relevant state, or the controls are not exposed as buttons.
  • Fix: wait for a meaningful selector, inspect the target surface and locale, then compare getByRole('button') with locator('button').

A named role locator is ambiguous

  • Cause: multiple controls share the same accessible name.
  • Fix: scope to a container, refine the name, or use evaluateAll() intentionally for a collection.

The native query misses a visible control

  • Cause: the control is a link, custom element, or another tag with button semantics.
  • Fix: use getByRole('button') and inspect its tag in the mapped output.

The script times out on Google

  • Cause: a consent screen, bot check, slow resource, or locale-specific page prevents the expected state.
  • Fix: capture a trace or screenshot, verify the URL and session state, and wait for a selector that exists on that variant. Do not replace a timeout with brittle class selectors.

Results change between runs

  • Cause: personalized content, experiments, viewport differences, or controls added after initial rendering.
  • Fix: fix browser context settings, collect after the same state transition, and record URL, locale, viewport and timestamp with the extracted data.

XPath cannot find a control

  • Cause: the control is inside an open shadow root or the XPath depends on a changed structure.
  • Fix: switch to a Playwright role/CSS locator or query the shadow host’s supported surface.

Performance, reliability and data quality

  • Prefer one page-context extraction: evaluateAll() maps the collection in one browser-context call, avoiding a separate round trip for every attribute.
  • Limit the scope: querying a known region reduces unrelated controls and makes the output easier to compare.
  • Keep snapshots explicit: store the URL, viewport, locale, consent/session condition and the event that triggered collection.
  • Do not infer stability: an extracted class, label or tag describes this rendered state, not a permanent Google API contract.
  • Separate semantic and visual requirements: accessible controls, native tags and visible controls are three different sets. Test the set your application actually needs.

Or skip the browser setup

If you only need a rendered image of Google or another URL—not DOM-level button data—ScreenshotNeo makes a single HTTP request and returns PNG, JPEG, WebP or PDF. It accepts the cookie/consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result.

Use the API documentation at https://screenshotneo.com/docs/ for all options. A minimal call is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://www.google.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://www.google.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://www.google.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
require('fs').writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. Every plan includes its features: 1,000 screenshots per month are free with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account to try it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When to use each approach

Goal Recommended method What it returns
Inventory controls users can access getByRole('button').evaluateAll() Semantic buttons, including eligible custom controls
Inventory only native tags locator('button').evaluateAll() HTML <button> elements
Inventory visible native tags locator('button:visible').evaluateAll() Visible native buttons at collection time
Inspect one known control Role plus accessible name A strict, user-facing target
Get a visual capture instead of DOM data ScreenshotNeo API PNG, JPEG, WebP or PDF

Frequently Asked Questions

Does getByRole(‘button’) return links styled to look like buttons?

Only if the element is exposed to accessibility APIs with the button role. Visual styling alone does not change its semantic role.

Can Playwright extract buttons from Google Search results and Lens?

It can inspect whichever page surface you open, but the available controls depend on product, device, locale, viewport and session state. Scope and verify the exact surface rather than assuming the same inventory.

Should I use innerText instead of textContent?

Use textContent for a predictable DOM extraction. If rendered visibility or layout-sensitive text matters, inspect the resulting output against the page state and the control’s accessible name.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.