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

To scrape JavaScript-rendered content with PhantomJS, create a webpage object, load the URL with page.open, verify that its callback reports success, wait until the page-specific content is actually present, and then call page.evaluate to read the rendered DOM. Return only strings, numbers, booleans, arrays, or plain objects that can cross PhantomJS’s JSON serialization boundary.

This method is mainly useful when you must maintain an existing PhantomJS job. PhantomJS development is suspended, its GitHub repository was archived on May 30, 2023, and the project wiki describes the 2.x branch as deprecated and no longer maintained. For a new scraper, use a maintained browser automation tool; the walkthrough below shows the legacy technique accurately so you can keep or migrate an existing script safely.

What PhantomJS can and cannot scrape

PhantomJS is a scriptable headless WebKit browser. Unlike an HTTP client that receives only the initial HTML response, it executes the page’s JavaScript and exposes the resulting document to your script. That makes it possible to extract text or attributes inserted after the first response.

The key limitation is timing: the page.open callback tells you that loading finished with a success or fail status. It does not establish that a single-page application has completed every API request or rendered the component you need. Your scraper must identify a meaningful, site-specific ready state before extraction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

The official APIs are page.open, which opens a URL and loads it, and page.evaluate, which evaluates a function in the page context.

Minimal working scraper

Save this as scrape.js and run it with the PhantomJS 2.x executable:

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

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

  // Confirm the page-specific content is present before extracting.
  var result = page.evaluate(function () {
    var heading = document.querySelector('h1');
    return {
      title: document.title,
      heading: heading ? heading.innerText : ''
    };
  });

  console.log(JSON.stringify(result));
  phantom.exit();
});

The callback checks the documented status and exits with a non-zero code on failure. Inside page.evaluate, normal DOM APIs such as document.querySelector inspect the rendered page. Outside that function, JSON.stringify prints the returned object as machine-readable output.

Install and run an existing PhantomJS 2.x setup

  1. Install the PhantomJS 2.x binary appropriate for your operating system, or use the binary already required by your legacy application.
  2. Put the script in a file, for example scrape.js.
  3. Run phantomjs scrape.js.
  4. Check the process exit code and parse the JSON line emitted by the script.

PhantomJS’s project repository states, “Important: PhantomJS development is suspended until further notice.” The repository is archived at github.com/ariya/phantomjs; the project wiki at the official wiki records the deprecated, unmaintained 2.x status. Treat this code as maintenance guidance, not a recommendation for a new production stack.

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

Wait for dynamic content before calling evaluate

A common error is to call page.evaluate immediately after page.open and receive an empty list. The page may have loaded its shell while an XHR, fetch request, or client-side render is still pending.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Choose a real readiness signal

  • A result container exists, such as #product-list.
  • A loading element has disappeared, such as .spinner.
  • A known status text changes from “Loading” to a completed state.
  • A page-specific global value or DOM attribute indicates that the application finished its request.

Use the signal that represents the data you need, not an arbitrary delay. The official page.open documentation defines the load callback and status, but it does not define one universal selector-wait API or a fixed sleep that works for every site. Consequently, the exact polling or event code must be designed for your target and verified against that target’s behavior.

Make extraction tolerant of missing elements

Selectors can change and some records may omit fields. Check each node before reading it and return an empty string, null, or another explicit value when it is absent. Keep the extraction function focused on the fields you actually need.

var rows = page.evaluate(function () {
  var nodes = document.querySelectorAll('.result');
  var output = [];
  for (var i = 0; i < nodes.length; i++) {
    var title = nodes[i].querySelector('.title');
    var price = nodes[i].querySelector('.price');
    output.push({
      title: title ? title.textContent.trim() : '',
      price: price ? price.textContent.trim() : ''
    });
  }
  return output;
});
console.log(JSON.stringify(rows));

The evaluate serialization boundary

page.evaluate runs in the web page’s JavaScript context, while your PhantomJS code runs outside it. Only JSON-serializable arguments and return values cross that boundary.

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

Safe return values

  • Strings, numbers, booleans and null.
  • Arrays containing serializable values.
  • Plain objects whose properties contain those values.

Values that do not cross reliably

  • DOM nodes such as an HTMLDivElement.
  • Functions and closures.
  • Complex browser objects that are not plain JSON data.

Convert a node to text or attributes inside the evaluated function, then return the resulting data. Do not try to return the node itself. Arguments passed into evaluate must follow the same serialization rule.

Console output is separate

A console.log executed inside the page context is not automatically the same as output from the PhantomJS script. If you need page-console messages, configure PhantomJS’s onConsoleMessage handler. For scraper output, it is usually clearer to return data from evaluate and print it outside, as in the examples.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Extracting text, links and attributes

Read rendered text with textContent or innerText, depending on whether you want hidden text excluded. Read URLs and other metadata with getAttribute or the element property.

var article = page.evaluate(function () {
  var link = document.querySelector('article a');
  return {
    heading: (document.querySelector('article h1') || {}).innerText || '',
    summary: (document.querySelector('article .summary') || {}).textContent || '',
    href: link ? link.href : ''
  };
});
console.log(JSON.stringify(article));

Keep normalization inside the page context when it depends on the DOM (for example, trimming whitespace or resolving a relative link), and keep file writing, database inserts and process control outside it.

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

Troubleshooting missing or incorrect data

status is fail

Cause: PhantomJS could not complete the navigation. Fix: log the URL, stop extraction, and investigate DNS, TLS, redirects, proxy settings, robots or server availability. Do not parse a partially loaded page as valid data.

The callback is successful but fields are empty

Cause: application JavaScript has not rendered the fields, or the selector no longer matches. Fix: inspect the selector in a browser, identify a target-specific ready signal, and extract only after that state is reached.

Only the initial shell is returned

Cause: the site populates content through later API calls or relies on browser capabilities older WebKit does not implement. Fix: inspect network and console errors, confirm that the target supports PhantomJS’s engine, and consider migrating to a maintained browser when compatibility is the issue.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The script prints undefined or an unusable object

Cause: the evaluated function returned a DOM node, function, closure or another non-serializable value. Fix: map the result to plain strings, numbers, booleans, arrays and objects before returning it.

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.

Page logs do not appear

Cause: page-context console messages are not forwarded automatically. Fix: set page.onConsoleMessage, or return diagnostic values from evaluate and print them in the outer script.

Selectors work manually but fail intermittently

Cause: a race between navigation and asynchronous rendering. Fix: wait for a meaningful application state, record timestamps and page URL, and make retries bounded. A fixed sleep may hide the race on a fast run and fail on a slow one.

Reliability, performance and data-quality practices

  • Validate the status first: never treat a fail callback as a successful empty result.
  • Use narrow selectors: stable IDs or semantic containers are less fragile than deeply nested positional selectors.
  • Return compact records: extracting only required fields reduces serialization and downstream work.
  • Record provenance: store the requested URL, final page URL when available, capture time and scraper version with each record.
  • Bound waiting and retries: prevent a single stalled page from blocking a batch indefinitely.
  • Respect access controls: follow the target site’s terms, authentication requirements and applicable law.
  • Plan migration: old WebKit behavior, modern JavaScript syntax and security changes can make results diverge over time.

Because PhantomJS is suspended and archived, you should budget engineering time for porting selectors and readiness logic to a maintained browser automation system. The longer a job remains on an unmaintained engine, the more likely a target-site change will become a production incident.

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

Keep PhantomJS or migrate?

Question Keep an existing PhantomJS job Migrate a new or changing job
Maintenance status Works only while your binary and target remain compatible; project development is suspended. Prefer a maintained browser project with current security and JavaScript support.
Migration effort No immediate porting; preserve existing selectors and deployment. Port selectors, readiness checks, page events and browser-launch code.
Dynamic readiness You must implement target-specific detection around page.open. Choose tooling with actively documented waits and events.
Compatibility risk Increasing risk from modern sites and deprecated WebKit behavior. Usually better aligned with current frameworks, subject to the chosen tool.

For a stable internal legacy task with a controlled target, retaining PhantomJS can be a pragmatic short-term choice. For a new scraper, a frequently changing site or a security-sensitive deployment, migration is the safer direction.

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.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server when your requirement is a rendered page image or PDF rather than structured DOM records. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets; those steps 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 result. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

One GET request returns PNG, JPEG, WebP or PDF. See the ScreenshotNeo API documentation for all options, including full-page lazy-image loading, CSS-selector element capture, device presets, retina scale, PDF paper and page-range controls, custom CSS and JavaScript, click and hide actions, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparency, resizing, TTL caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting and the OpenAPI specification.

cURL

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

Python

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)

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

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free. Create a free ScreenshotNeo account to get started.

Frequently asked questions

Does PhantomJS execute JavaScript?

Yes. It runs page scripts in its headless WebKit browser, which is why page.evaluate can inspect a rendered DOM. Its engine is old and the project is no longer maintained, so modern-site compatibility is not assured.

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

Can I return an element from page.evaluate?

No. Convert the element to serializable data such as text, attributes or a plain object inside the evaluated function.

Is page.open success proof that scraping is complete?

No. It reports navigation completion status. Dynamic applications may still be rendering content afterward; use a target-specific readiness condition.

Is PhantomJS suitable for a new scraper?

Generally no. The repository is archived and development is suspended. It remains useful for understanding or temporarily maintaining an existing script while you plan migration.

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.