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

Use await page.evaluate() after launching Pyppeteer, opening a page, and navigating to a URL. Pass JavaScript as a string containing either a function or an expression; add function arguments after that string. Pyppeteer executes the code in the browser’s page context and converts the returned value into a Python value.

Minimal working example

Install Pyppeteer, launch Chromium, create a page, navigate, evaluate JavaScript, print the result, and close the browser:

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('https://example.com')

    title = await page.evaluate('''() => document.title''')
    greeting = await page.evaluate('''(name) => `Hello, ${name}`''', 'Ada')
    print(title, greeting)

    await browser.close()

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

The important details are the await before page.evaluate(), the JavaScript string, and the arguments supplied after the function string. Evaluation occurs inside the loaded page, so browser globals such as document, window, and the DOM are available.

What page.evaluate() does

Pyppeteer’s API executes a JavaScript function or expression in the browser and returns its result to Python. Simple values and JSON-compatible objects are serialized across the browser boundary. A returned object such as {width, height} becomes a Python dictionary; a returned array becomes a Python list.

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

Read page dimensions

dimensions = await page.evaluate('''() => {
    return {
        width: document.documentElement.clientWidth,
        height: document.documentElement.clientHeight,
        deviceScaleFactor: window.devicePixelRatio,
    }
}''')
print(dimensions)

The values describe the current page and viewport, not the dimensions of an image or PDF produced later. Set the viewport before evaluating if your result depends on responsive layout.

Function strings and expression strings

Pyppeteer accepts JavaScript as a string and attempts to determine whether the string is a callable function or a direct expression. Arrow functions and regular functions are the clearest form when you need parameters, statements, or a return value:

result = await page.evaluate('''(a, b) => {
    const total = a + b
    return total * 2
}''', 2, 3)
print(result)  # 10

A direct expression is useful for a single property or calculation:

content = await page.evaluate('document.body.textContent', force_expr=True)

Use the keyword-only option force_expr=True when Pyppeteer misidentifies an expression as a function. This is especially useful for strings beginning with an identifier, property access, or another expression that does not look like an arrow or regular function.

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

Choosing the form

  • Function string: use () => ... or (value) => ... for arguments, multiple statements, conditionals, and explicit returns.
  • Expression string: use a short expression such as document.title; add force_expr=True if detection is ambiguous.
  • Async browser code: make the callback async when it must await a promise, then await the Python call as usual.
data = await page.evaluate('''async () => {
    const response = await fetch('/api/status')
    return await response.json()
}''')

The page’s origin, cookies, permissions, and content-security behavior still apply to code running in that page. A failed fetch or rejected promise is a browser-side failure that Pyppeteer reports back to Python.

Passing arguments safely

Every positional value after the JavaScript string is serialized and supplied to the callback in order:

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
result = await page.evaluate(
    '''(a, b) => a + b''',
    2,
    3,
)

Pass structured data as normal Python dictionaries and lists when their contents are serializable:

config = {'selector': 'h1', 'uppercase': True}
text = await page.evaluate('''(options) => {
    const node = document.querySelector(options.selector)
    if (!node) return null
    const value = node.textContent.trim()
    return options.uppercase ? value.toUpperCase() : value
}''', config)

Do not pass Python functions, open files, sockets, or arbitrary class instances as callback arguments. Convert them to strings, numbers, booleans, lists, or dictionaries first.

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

Evaluating against a selected element

Find an element handle, then pass that handle as the first callback argument:

element = await page.querySelector('h1')
if element is None:
    raise RuntimeError('No h1 element found')

text = await page.evaluate(
    '''(element) => element.textContent''',
    element,
)
print(text)

The handle refers to a DOM node in the page. It is not a copy of the element, and it becomes invalid if navigation replaces the document.

Use querySelectorEval() for one operation

querySelectorEval(selector, pageFunction, *args) combines selection and evaluation. The matching element is passed as the first callback argument:

text = await page.querySelectorEval(
    'h1',
    '''(element, suffix) => element.textContent.trim() + suffix''',
    '!',
)

If no element matches, this method raises an element error. Use an explicit querySelector() check when “not found” is an expected outcome that your code should handle.

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

Related Pyppeteer APIs

API Use it when Result or timing
evaluate() You need a one-off calculation, DOM read, mutation, or returned value. Returns a serialized value immediately after the JavaScript finishes.
evaluateHandle() The result is an in-page object you will inspect or manipulate through the DevTools protocol. Returns a persistent JSHandle, not a copied Python value.
evaluateOnNewDocument() Code must be installed before navigation or in newly attached child frames. Registers code that runs for future document loads.
waitForFunction() You need to wait until a browser-side condition becomes truthy. Polls a predicate rather than performing a single evaluation.

Persistent handles

handle = await page.evaluateHandle('''() => window.localStorage''')
# Use handle with other Pyppeteer operations, then dispose it when finished.
await handle.dispose()

Prefer evaluate() when you only need data in Python. Handles keep a reference in the browser and should be disposed when no longer needed.

Inject code before a page loads

await page.evaluateOnNewDocument('''() => {
    window.myAutomationFlag = true
}''')
await page.goto('https://example.com')

This is different from calling evaluate() after navigation: the registered script runs during subsequent document creation, including child frames.

Waiting for dynamic content

Evaluation sees the DOM at the instant it runs. For client-rendered pages, wait for a selector or a predicate first:

await page.waitForSelector('.product-card')
count = await page.evaluate('''() => document.querySelectorAll('.product-card').length''')
await page.waitForFunction('''() => {
    return document.querySelectorAll('.product-card').length >= 10
}''')

Use a selector wait when a specific node signals readiness. Use waitForFunction() for a value that must become true, such as a minimum item count or a global application flag. Add an explicit timeout appropriate to the site so a broken page does not wait forever.

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

Common errors and fixes

“Evaluation failed” or syntax errors

  • Check the JavaScript string for unmatched quotes, braces, or backticks.
  • Use a function form with an explicit return for multi-line code.
  • Run a plain property expression with force_expr=True.

The result is None

JavaScript returns undefined when a function has no return statement. Add return value; also check that a selector actually matched an element.

Element handle errors

A handle can be None because the selector matched nothing, or stale because navigation replaced the document. Wait for the selector and reacquire the handle after every navigation.

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

Timeouts

Evaluation itself is usually quick, but JavaScript that waits on a network request or an unresolved promise can exceed the page timeout. Add error handling around the call, set a bounded timeout, and verify that the page’s request is reachable from the browser context.

Cross-origin frames

An element belongs to its own frame. Obtain the appropriate frame and evaluate there rather than assuming the main page document contains the node. Browser security rules still prevent unrestricted access across origins.

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

Serialization surprises

DOM nodes, functions, symbols, and cyclic objects cannot be returned as ordinary JSON data. Return the specific fields you need, such as textContent, attributes, or an array of plain objects.

Reliability and performance practices

  • Navigate first and wait for the application state your script requires.
  • Keep callbacks small; perform heavy parsing in Python after returning compact data.
  • Return plain serializable values instead of large DOM subtrees.
  • Reuse a browser and page for related operations, but close both in a finally block during failures.
  • Release JSHandle objects with dispose().
  • Make selectors specific and resilient to cosmetic class-name changes.
  • Log the URL, selector, and a short error message when an evaluation fails; avoid logging credentials or page secrets.
async def read_title(url):
    browser = await launch()
    try:
        page = await browser.newPage()
        await page.goto(url, {'waitUntil': 'networkidle2'})
        return await page.evaluate('''() => document.title''')
    finally:
        await browser.close()

The exact navigation wait setting should match the application. Network-idle waits can be unsuitable for pages with continuous analytics or streaming requests; a specific selector or predicate is often more deterministic.

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 actual goal is a clean screenshot rather than arbitrary in-page automation, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.

One GET request returns PNG, JPEG, WebP, or PDF. The API supports full-page captures with lazy images, CSS-selector element shots, dark mode, device presets and custom viewports, retina scale, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

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.

See the ScreenshotNeo documentation for authentication and all parameters:

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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to start.

FAQ

Can I call a Python function inside the page?

No. The callback executes JavaScript in Chromium. Pass data from Python as serialized arguments, then return serialized results.

Does evaluate() automatically wait for a selector?

No. Call waitForSelector() or waitForFunction() before evaluating dynamic content.

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

When should I use querySelectorEval()?

Use it for a concise selector-plus-callback operation when a missing element should raise an error.

Frequently Asked Questions

Can I call a Python function inside the page?

No. The callback executes JavaScript in Chromium. Pass data from Python as serialized arguments, then return serialized results.

Does evaluate() automatically wait for a selector?

No. Call waitForSelector() or waitForFunction() before evaluating dynamic content.

When should I use querySelectorEval()?

Use it for a concise selector-plus-callback operation when a missing element should raise an error.

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

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.