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 PhantomJS’s page.open() to load the page, check that its callback reports success, and then call page.evaluate() to find the button and invoke its DOM click() method. The selector and any wait after the click must match the target page.
The basic PhantomJS pattern
PhantomJS separates browser automation into two contexts. Your script runs in PhantomJS, while the function passed to page.evaluate() runs inside the loaded document. Browser-only objects such as document, window, and DOM elements are available only in that page context.
- Create a WebPage object with
require('webpage').create(). - Call
page.open(url, callback). - In the callback, stop if the status is not
success. - Use
page.evaluate()to select the button and callclick(). - Keep PhantomJS running until any navigation or asynchronous update caused by the click has completed.
This complete example reports whether a uniquely identified button was found:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
var page = require('webpage').create();
page.open('https://example.com', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
phantom.exit();
return;
}
var clicked = page.evaluate(function () {
var button = document.querySelector('button#submit');
if (!button) {
return false;
}
button.click();
return true;
});
console.log(clicked ? 'Button found and clicked' : 'Button not found');
phantom.exit();
});
Replace https://example.com and button#submit with the real URL and selector. The sample is an API-pattern illustration, not a test against a live target.
#1 Best Overall
- 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
Choose a selector that identifies the intended button
ID and attribute selectors
An ID is usually the narrowest choice: button#submit. If the page uses a stable attribute, select it directly:
document.querySelector('button[data-action="save"]')
Use a class only when it is specific enough. A generic class such as .btn may match several controls.
Text-based selection
CSS selectors do not select by visible text. If no stable attribute exists, inspect all candidate buttons and compare their trimmed textContent:
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →var clicked = page.evaluate(function () {
var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].textContent.replace(/^s+|s+$/g, '') === 'Continue') {
buttons[i].click();
return true;
}
}
return false;
});
This approach is sensitive to localization, capitalization, and whitespace. Prefer a data attribute or ID when you control the page.
Links styled as buttons
Some interfaces use an <a> element rather than <button>. Select the actual element, for example a#continue, and call its click() method. Do not assume that a visual button is a button element.
Understanding the evaluate boundary
page.evaluate(function, arg1, arg2, ...) evaluates the supplied function in the webpage context and returns a value to the PhantomJS script. Pass only simple, serializable values such as strings, numbers, booleans, arrays, and plain objects.
- Do not pass a DOM node from the outer script into
evaluate(). - Closures and functions from the outer script do not cross the boundary.
- Return a boolean, string, number, or plain object rather than a DOM object.
- Keep the function self-contained; resolve selectors and perform the click inside it.
For diagnostics, return structured information:
var result = page.evaluate(function () {
var button = document.querySelector('button#submit');
if (!button) {
return { found: false, ready: document.readyState };
}
if (button.disabled) {
return { found: true, disabled: true };
}
button.click();
return { found: true, disabled: false };
});
console.log(JSON.stringify(result));
Clicking with jQuery
The PhantomJS automation guide also demonstrates loading jQuery with page.includeJs() and then calling jQuery inside page.evaluate(). The external script’s callback is important: do not exit before jQuery has loaded.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesRank #2
- 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
var page = require('webpage').create();
page.open('https://example.com', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
phantom.exit();
return;
}
page.includeJs('https://example.com/jquery.js', function () {
var clicked = page.evaluate(function () {
var button = $('button#submit');
if (!button.length) {
return false;
}
button.click();
return true;
});
console.log(clicked ? 'Button found and clicked' : 'Button not found');
phantom.exit();
});
});
The broad example $('button').click() clicks every matching button. A narrower selector avoids submitting, cancelling, or navigating through unintended controls. Use a jQuery URL that the target page can actually load, and account for any site policy that blocks external scripts.
When the click triggers navigation or asynchronous work
A successful call to click() proves only that the handler was invoked. It does not prove that a request finished, a new view rendered, or a form submission succeeded.
Navigation
If the click changes location, observe the new page with PhantomJS’s page callbacks or a short polling loop before reading its content. Keep the process alive instead of calling phantom.exit() immediately after the click. The exact navigation behavior depends on the target page and its event handlers.
DOM updates
For an AJAX-style update, poll for a specific, meaningful state: a result element appearing, a loading class disappearing, or a status attribute changing. A fixed delay can work for a known environment but is less reliable when network time varies.
Recommended Free Tools
function waitForResult(attemptsLeft) {
var ready = page.evaluate(function () {
var result = document.querySelector('#result');
return !!result && result.textContent.replace(/^s+|s+$/g, '') !== '';
});
if (ready) {
console.log('Result is ready');
phantom.exit();
return;
}
if (attemptsLeft <= 0) {
console.log('Timed out waiting for result');
phantom.exit();
return;
}
setTimeout(function () {
waitForResult(attemptsLeft - 1);
}, 250);
}
page.open('https://example.com', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
phantom.exit();
return;
}
page.evaluate(function () {
var button = document.querySelector('button#submit');
if (button) {
button.click();
}
});
waitForResult(40);
});
The loop above waits for a page-specific condition for up to 40 checks at 250 milliseconds each. Choose a condition and timeout that reflect the application rather than treating the delay as universal.
Pointer-level interactions
A DOM click is concise and works for ordinary event handlers. It does not necessarily reproduce every pointer sequence, coordinate check, hover state, or gesture. If the target depends on actual mouse movement or a particular event order, investigate PhantomJS’s page.sendEvent API and verify the exact arguments against the PhantomJS version installed. Do not assume that a DOM click is equivalent to a physical browser interaction.
Troubleshooting common failures
Unable to access network
Cause: page.open() returned a status other than success.
Rank #3
- 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.
Fix: Stop before calling evaluate(), verify the URL and network access, and log the returned status. A page that did not load cannot provide a dependable DOM.
Free tools Windows power users keep installed
One-click scans. No signup required.
“Button not found”
Cause: The selector is wrong, the control is rendered later, or the element is inside a frame or another document.
Fix: Confirm the exact tag, ID, and attributes in the page source or inspector. Check the document after it has loaded, and account for controls created by page scripts. If the control is in a frame, inspect that frame’s document rather than the top-level document.
The selector matches the wrong control
Cause: A generic class, tag selector, or broad jQuery expression matched multiple elements.
Fix: Narrow the selector with an ID, data attribute, parent relationship, or exact text comparison. Return a count or diagnostic object from evaluate() while debugging.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →The click does nothing
Cause: The control is disabled, an application-specific condition is unmet, or the page requires pointer events rather than a DOM activation.
Fix: Check button.disabled and the surrounding DOM state. If the site relies on coordinates, hover, or a particular event sequence, investigate page.sendEvent and confirm its signature for your installed version.
Rank #4
- 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
Results are read too early
Cause: The script exits or inspects the page immediately after triggering asynchronous work.
Fix: Wait for a concrete result element or state change, with a bounded timeout, before collecting output or taking a screenshot.
jQuery is undefined
Cause: page.evaluate() ran before page.includeJs() completed, or the external script failed to load.
Fix: Put the evaluation inside the includeJs callback and use a script URL accessible from the target environment.
Operational considerations
Reliability
Use deterministic selectors, explicit status checks, bounded waits, and diagnostic return values. Treat a reported click as a trigger, not as proof of a completed transaction. Test selectors against the actual version of the page you automate because markup and client-side behavior can change.
Performance
Loading an external library adds a network dependency; native DOM selection avoids that extra request. Poll only as often as necessary, and stop polling as soon as the expected state appears. A short, page-specific script is easier to retry than a script that sleeps for an arbitrary long interval.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchSecurity and data handling
Keep credentials out of page source and selectors. Be cautious when opening URLs or executing page-provided JavaScript, especially when input URLs come from users. Return only the small values your outer script needs across the evaluation boundary.
Best Value
- 【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.
Or skip the browser setup
If your goal is a dependable screenshot after a page interaction, ScreenshotNeo provides a website screenshot API and MCP server. Its capture options include custom JavaScript and clicking an element before capture, so you can keep the browser orchestration in the request rather than maintaining a PhantomJS script. The API also supports full-page captures, selected elements, device and viewport settings, waits, cookies, headers, and PDF output.
One basic request is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for the JavaScript, waiting, and click options when the target requires them. The same request from 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,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
And 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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing state. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account to try it.
FAQ
Can I call page.evaluate() before page.open() finishes?
No. Wait for the page.open() callback and verify its status before inspecting or changing the document.
Does button.click() submit every form?
It activates the selected element only. Whether that submits a form, starts JavaScript, or does nothing depends on the page’s handlers and current state.
How do I know whether the click completed?
Define a page-specific completion condition, such as a result node or navigation state, and wait for that condition with a timeout.
Frequently Asked Questions
Can I call page.evaluate() before page.open() finishes?
No. Wait for the page.open() callback and verify its status before inspecting or changing the document.
Does button.click() submit every form?
It activates the selected element only. The page’s handlers and current state determine the result.
How do I know whether the click completed?
Wait for a page-specific completion condition, such as a result node or navigation state, with a bounded timeout.
Quick Recap
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.

