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

To click a link in PhantomJS, open the starting URL with page.open(), find the anchor inside page.evaluate(), call its DOM click() method, and monitor page.onLoadFinished for the resulting document load. Add page.onNavigationRequested when you need the destination and navigation type. If the link creates a new window, handle that page through page.onPageCreated instead of treating it as navigation in the original page.

Complete same-page navigation example

The following script loads a page, clicks a.next, reports navigation attempts, and logs the URL when loading finishes. Save it as click-next.js and run it with the PhantomJS executable.

var page = require('webpage').create();

page.onNavigationRequested = function (url, type, willNavigate, main) {
  console.log('Target: ' + url +
    '; type: ' + type +
    '; will navigate: ' + willNavigate +
    '; main frame: ' + main);
};

page.onLoadFinished = function (status) {
  console.log('Load finished: ' + status);
  if (status === 'success') {
    console.log('Current URL: ' + page.url);
  }
};

page.open('https://example.com/start', function (status) {
  if (status !== 'success') {
    console.log('Could not load the starting page');
    phantom.exit(1);
    return;
  }

  var clicked = page.evaluate(function () {
    var link = document.querySelector('a.next');
    if (!link) {
      return false;
    }
    link.click();
    return true;
  });

  if (!clicked) {
    console.log('The link selector did not match an element');
    phantom.exit(1);
  }
});

PhantomJS’s WebPage.open callback receives success or fail after the initial load. The callback does not return a page object; the page is the object you created with require('webpage').create(). Install handlers before calling open, so they can observe both the initial document and a later navigation.

How the click works

Run DOM code in the page context

page.evaluate() executes its function inside the loaded document. That is where document.querySelector() and link.click() belong. The function’s arguments and return value must be simple serializable values. Return a boolean, string, or number; do not return a DOM element, function, or other browser object. The evaluated function also cannot read variables from the outer PhantomJS script unless you pass them as arguments.

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

Choose a selector that identifies the real link

a.next means an anchor element with the next class. Other useful selectors include a[rel="next"], nav.pagination a[aria-label="Next"], or an exact URL such as a[href="/page/2"]. Check the selector in the site’s HTML and make it specific enough to avoid clicking an unrelated link.

Check the match before clicking

querySelector() returns null when nothing matches. The example converts that condition into false and exits with an error rather than silently continuing. If several links can match, use querySelectorAll() and inspect text, attributes, or position inside the evaluated function before selecting one.

Knowing when the next page is ready

Use onLoadFinished for document completion

page.onLoadFinished receives success when the document load completed without a network error and fail otherwise. Read page.url after a successful event to confirm the destination. A successful load event is evidence that the document loaded; it is not a guarantee that a single-page application has completed its own asynchronous rendering.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Wait for an application condition when needed

Some sites change the URL or content through client-side JavaScript without performing a conventional full document load. If your task requires a particular result—such as a product grid, a heading, or a logged-in state—poll for that site-specific condition in the page and stop only when it appears. The PhantomJS references do not define a universal timeout or retry interval, so choose a limit appropriate to the site and fail clearly when it is exceeded.

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

Log attempted destinations with onNavigationRequested

page.onNavigationRequested = function (url, type, willNavigate, main) {
  console.log('Target: ' + url);
  console.log('Type: ' + type);
  console.log('Will navigate: ' + willNavigate);
  console.log('Main frame: ' + main);
};

The navigation handler reports an attempted navigation. Its type can identify actions such as LinkClicked, FormSubmitted, BackOrForward, Reload, or Other. willNavigate tells you whether navigation is allowed; false means it is locked. The callback does not perform the click and does not replace load-completion handling.

Links that open a new window

A link using window.open() creates a child page rather than navigating the existing page. Register page.onPageCreated and attach handlers to the supplied page:

page.onPageCreated = function (newPage) {
  newPage.onLoadFinished = function (status) {
    console.log('Child page load: ' + status +
      ', URL: ' + newPage.url);
  };
};

Install this handler before opening and clicking. Keep a reference to the child page if later code must inspect its DOM, close it, or wait for a particular element. The original page’s onLoadFinished does not describe the child window’s load.

Reliable workflow for a real site

  1. Create the page and register handlers. Add onLoadFinished for completion, onNavigationRequested for diagnostics, and onPageCreated if new windows are possible.
  2. Open the starting URL. Call page.open(url, callback) and stop on fail. Do not interact before the callback reports success.
  3. Verify the starting document. In an evaluated function, check a distinctive element, title, or page marker if the URL can return an error page.
  4. Click in evaluate. Find the intended anchor, optionally inspect its text or href, call click(), and return a serializable success flag.
  5. Observe the result. Use the load handler for a normal navigation, navigation logging for the requested target, or a child-page handler for window.open.
  6. Apply an application-ready check. For AJAX or single-page applications, wait for the actual element or state your automation needs rather than assuming the document event is sufficient.
  7. Exit deliberately. Call phantom.exit(0) after your success condition and phantom.exit(1) on a failed load, missing selector, blocked navigation, or timeout.

Troubleshooting

“The link selector did not match an element”

  • Inspect the final HTML and correct the selector, including case-sensitive class names.
  • If the link is injected after load, wait for its container or poll until it exists.
  • Confirm that the link is in the main document, not an iframe; a frame requires separate page/frame handling.

The click runs but the URL does not change

  • The site may handle the click with AJAX. Wait for a content or state change instead of relying on a new document URL.
  • onNavigationRequested may report willNavigate: false, indicating navigation was locked.
  • The handler may be observing a child window; add onPageCreated.

onLoadFinished reports fail

  • Check the starting URL, DNS/TLS access, redirects, and whether the site blocks the PhantomJS user agent.
  • Log the requested URL and navigation type to distinguish a bad target from a blocked transition.
  • Do not retry indefinitely; set an application-level limit and report the failure.

The page loads but content is incomplete

A load event can precede later asynchronous work. Wait for a concrete selector or state, and treat a missing condition after your chosen limit as an error. There is no universal PhantomJS timeout established by the API references.

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

Local PhantomJS versus hosted helpers

The local PhantomJS API uses WebPage.evaluate for DOM scripting and CSS selectors, as described in the Quick Start and WebPage documentation. PhantomJS Cloud’s Advanced Automation Samples show service-specific helpers such as page.click and waitForNavigation. Those helpers are not built-in methods of a local PhantomJS WebPage; do not paste a hosted-service example into a local script unchanged.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For a one-off page image or an automated capture pipeline, ScreenshotNeo returns a screenshot or PDF from one HTTP request. Its API accepts a URL and supports PNG, JPEG, WebP, and PDF output; it can also wait for selectors, delays, or network idle and capture a specific element.

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 parameters and output options. Equivalent calls:

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}`);

Before capture, ScreenshotNeo accepts cookie or consent banners 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. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for 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.

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.

Create a free ScreenshotNeo account to start with 1,000 screenshots a month and no card.

PhantomJS clicking checklist

  • Open the page and verify the callback status.
  • Register load and navigation handlers before opening.
  • Run selector lookup and click() inside page.evaluate().
  • Return only serializable values from evaluated code.
  • Use onLoadFinished for document completion and a site-specific condition for SPA readiness.
  • Handle window.open with onPageCreated.
  • Exit with an explicit success or failure code.

Frequently Asked Questions

Does onNavigationRequested wait until the next page is loaded?

No. It reports an attempted navigation and its destination details. Use onLoadFinished, plus any application-specific readiness check, to decide when the result is usable.

Can I return the clicked anchor from page.evaluate()?

No. Return serializable data such as a boolean, URL string, or text. DOM elements and other browser objects cannot cross the evaluate boundary.

What handler is needed for target="_blank"?

Register page.onPageCreated and attach load or readiness handlers to the new page.

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.