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

Use Pyppeteer’s XPath lookup to select a button whose visible text matches your label. For an exact, whitespace-tolerant match, query //button[normalize-space(.)="Submit"], verify that exactly one element was returned, and then click it. Page.xpath() is the primary method; Page.Jx() is its shorthand.

The direct Pyppeteer solution

Pyppeteer returns a list of element handles from an XPath query. That means selecting by text is a two-step operation: write an XPath that describes the button, then inspect the result before clicking.

buttons = await page.xpath('//button[normalize-space(.)="Submit"]')

if len(buttons) != 1:
    raise RuntimeError(f"Expected one matching button, got {len(buttons)}")

await buttons[0].click()

normalize-space(.) compares the button’s complete string value while removing leading and trailing whitespace and collapsing repeated whitespace. The dot (.) includes text from descendants, so a button containing a nested <span> is still matched.

How Pyppeteer’s XPath methods work

Page.xpath()

await page.xpath(expression) evaluates an XPath expression in the page and returns a Python list of element handles. The expression can be restricted to button, which prevents a heading, link, or container with the same words from being selected accidentally.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
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

Page.Jx()

Page.Jx(expression) is the shorthand form of the same XPath lookup. Use whichever spelling makes your code clearer; both are Pyppeteer APIs corresponding to Puppeteer’s XPath lookup.

matches = await page.Jx('//button[normalize-space(.)="Submit"]')
if len(matches) == 1:
    await matches[0].click()

Exact text matching

Use an exact predicate when the label is known and should not match another action:

save_buttons = await page.xpath('//button[normalize-space(.)="Save changes"]')
if len(save_buttons) != 1:
    raise RuntimeError(
        f"Expected one Save changes button, got {len(save_buttons)}"
    )
await save_buttons[0].click()

Why use normalize-space(.)?

Rendered markup often contains indentation, line breaks, or several spaces around a label. An expression using text() can also miss text held in a child element. The string-value expression . sees the button’s descendant text, while normalize-space() makes harmless whitespace differences irrelevant.

XPath text comparisons are case-sensitive. A label of Submit does not match submit. If the application localizes its labels, use the expected locale-specific string or a more stable attribute instead of silently making the match broad.

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

Always check the count

A correct label is not proof that the selector is unique. Responsive layouts may render desktop and mobile controls together; a dialog and the page behind it may each contain a button with the same wording. Treat these outcomes differently:

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
  • Zero matches: the text may differ, the page may not have finished rendering, the control may be inside an iframe, or it may not be a button element.
  • One match: inspect whether it is visible and enabled, then click it.
  • More than one match: narrow the XPath with a container, an attribute, or an additional condition. Do not click the first result merely because it happens to work today.

Partial text matching

Use contains() only when a partial label is intentional:

matches = await page.xpath(
    '//button[contains(normalize-space(.), "Save")]'
)

if len(matches) != 1:
    raise RuntimeError(f"Expected one button containing Save, got {len(matches)}")
await matches[0].click()

This can match Save, Save changes, and Save as draft at the same time. Review every candidate when using a partial expression. During debugging, inspect the text of each returned handle:

for index, handle in enumerate(matches):
    label = await page.evaluate(
        '(element) => element.innerText', handle
    )
    print(index, repr(label))

If the wording is variable but an attribute is stable, combine the conditions instead of widening the text search:

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.
matches = await page.xpath(
    '//button[@data-action="save" and contains(normalize-space(.), "Save")]'
)

A complete runnable example

The following script creates a small page, selects the button by its text, clicks it, and verifies the resulting text. It uses an explicit count check so a selector regression fails loudly.

import asyncio
from pyppeteer import launch


async def click_button_by_text(page, label):
    expression = f'//button[normalize-space(.)="{label}"]'
    buttons = await page.xpath(expression)

    if len(buttons) != 1:
        raise RuntimeError(
            f"Expected one button named {label!r}, got {len(buttons)}"
        )

    await buttons[0].click()


async def main():
    browser = await launch(headless=True)
    page = await browser.newPage()
    await page.setContent("""
        <button id="save">
            <span>Save</span> changes
        </button>
        <p id="status">Not saved</p>
        <script>
            document.querySelector('#save').addEventListener('click', () => {
                document.querySelector('#status').textContent = 'Saved';
            });
        </script>
    """)

    await click_button_by_text(page, "Save changes")
    status = await page.Jeval('#status', 'element => element.textContent')
    assert status == 'Saved', status
    print(status)

    await browser.close()


asyncio.get_event_loop().run_until_complete(main())

In production code, avoid interpolating arbitrary user text directly into an XPath string. A label containing a quote needs an XPath-safe literal builder, or you can select a stable attribute with CSS and verify the text separately. For fixed labels in a test, the direct expression is usually sufficient.

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.

Waiting for a button that appears later

Querying immediately after navigation can return an empty list because the application has not inserted the control yet. Wait for the XPath, then perform the same uniqueness check:

button = await page.waitForXPath(
    '//button[normalize-space(.)="Continue"]',
    {'timeout': 10000}
)

# waitForXPath returns the first matching handle; use a fresh query
# when uniqueness matters.
buttons = await page.xpath('//button[normalize-space(.)="Continue"]')
if len(buttons) != 1:
    raise RuntimeError(f"Expected one Continue button, got {len(buttons)}")
await buttons[0].click()

Waiting for presence does not guarantee that the element is visible, enabled, or unobstructed. If a modal animation or an overlay is still active, wait for the application’s state to settle or remove the overlay through the same user-facing action a real visitor would use.

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

Buttons inside iframes

An XPath evaluated on the main page cannot see into an iframe’s document. Locate the desired frame first and run the XPath against that frame:

frame = next(
    frame for frame in page.frames
    if frame.url.endswith('/checkout')
)

buttons = await frame.xpath('//button[normalize-space(.)="Pay now"]')
if len(buttons) != 1:
    raise RuntimeError(f"Expected one Pay now button, got {len(buttons)}")
await buttons[0].click()

Choose a frame by a reliable URL, name, or other property. If the frame is created dynamically, wait until it exists before querying it.

When CSS is a better selector

Text is useful when it is the only stable identifier, but a unique attribute is generally less sensitive to translation and copy edits. Prefer CSS when the page exposes a stable ID, test attribute, or action attribute:

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
buttons = await page.querySelectorAll('button[data-testid="save"]')
if len(buttons) != 1:
    raise RuntimeError(f"Expected one save control, got {len(buttons)}")
await buttons[0].click()

You can still verify the visible label after selecting by CSS. Conversely, keep XPath when the requirement is explicitly user-facing text and no durable attribute exists.

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

When the control is not a <button>

Some interfaces make a clickable control from an anchor or a div. A button-only XPath will correctly return nothing in that case. Adapt the element test to the actual DOM, while retaining the text and count checks:

controls = await page.xpath(
    '//*[@role="button" and normalize-space(.)="Submit"]'
)
if len(controls) != 1:
    raise RuntimeError(f"Expected one role=button control, got {len(controls)}")
await controls[0].click()

If the wording is supplied in an attribute rather than descendant text, match that attribute instead. For example, an input submit control may expose its label through @value:

controls = await page.xpath(
    '//input[@type="submit" and normalize-space(@value)="Submit"]'
)

Troubleshooting selector failures

Symptom Likely cause Fix
Zero matches Whitespace, casing, or wording differs Print the rendered text, use normalize-space(.), and confirm the exact label.
Zero matches after navigation The control is rendered asynchronously Wait for the XPath or for an application-specific ready state before querying.
Several matches Duplicate responsive, hidden, or background controls Inspect each candidate and add a container, attribute, or state predicate.
Text appears on screen but XPath finds nothing The text is in an iframe, shadow DOM, or a non-button element Query the correct frame, use the component’s exposed DOM, or adapt the element test.
Click raises an interaction error The element is detached, hidden, disabled, or covered Re-query after the page settles, verify visibility and enabled state, and close the obstructing UI.
Click succeeds but nothing changes The control may require a different event or may be disabled by application state Check the DOM state and wait for the expected navigation, network request, or status change.

Reliability and maintenance practices

  • Keep the element type in the XPath when the requirement is specifically a button.
  • Use exact normalized text for a known action; reserve contains() for deliberately flexible labels.
  • Assert the number of matches before every important click.
  • Scope the expression to a dialog, form, or other stable container when duplicate labels are expected elsewhere.
  • Prefer stable attributes for long-lived tests when the product team can provide them.
  • After clicking, wait for an observable result—navigation, a status element, or a changed attribute—instead of assuming that a completed click means the workflow completed.

XPath selection itself does not come with a performance assumption or benchmark. The practical cost is usually dominated by page rendering, network activity, and the action that follows the click. Reducing broad, repeated queries and reusing a specific container can still make a busy test suite easier to diagnose.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to capture a page rather than interact with its buttons, ScreenshotNeo returns a screenshot or PDF through one request. It is not a replacement for a Pyppeteer click, but it avoids launching and maintaining a browser when you only need a clean visual result. The API documentation is at screenshotneo.com/docs/.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

For example, this cURL request captures Stripe as WebP:

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

The same request in Python is:

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

And in Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Before capture, ScreenshotNeo accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing result in headers. Its MCP server gives AI agents tools named take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

FAQ

Does normalize-space() handle every kind of whitespace?

It handles the normal XML whitespace characters used by XPath. A non-breaking space can remain distinct, so inspect the actual DOM text when a visually identical label still fails to match.

Can XPath find a disabled button?

Yes. Selection and usability are separate: XPath can return a disabled element, while the click may have no effect or raise an interaction error. Check the element’s disabled state before treating the action as successful.

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

Frequently Asked Questions

Does normalize-space() handle every kind of whitespace?

It handles normal XPath whitespace, but a non-breaking space may remain distinct. Inspect the DOM text if a visually identical label does not match.

Can XPath find a disabled button?

Yes. Finding an element does not make it usable; verify that it is enabled before clicking and wait for the application state that enables it.

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.