How to Capture a Full-Page Screenshot Using Selenium in Google Colab
Capture a full-page PNG in Colab with Selenium and Chrome’s DevTools Protocol, then save or download it before the temporary runtime ends.
To capture a full-page screenshot in Google Colab with Selenium and Chrome, use Chrome DevTools Protocol (CDP) through Selenium’s Chromium driver. Call Page.captureScreenshot with captureBeyondViewport enabled, decode the returned base64 data, and write the PNG to a file. Selenium’s regular save_screenshot() captures the current browser window and does not request this beyond-viewport behavior. Chrome DevTools Protocol: Page; Selenium Chromium WebDriver.
1. Set up Selenium and Chrome in Colab
Colab runtimes change over time, so there is no single Chrome installation command or binary path that is guaranteed for every runtime. First inspect the active runtime, then install or select a Selenium-compatible Chrome and driver using the setup appropriate to that image. Avoid copying a hard-coded browser path from an old notebook without checking it.
Put setup in notebook cells so collaborators can recreate the environment. Colab notes that a shared notebook does not share its VM, custom files, or installed libraries, and recommends including cells that install and load needed dependencies. See the Google Colab FAQ.
# Setup cell: install the Python library if it is not already available.
%pip install -q selenium
Start Chrome with Selenium after confirming that Chrome and a compatible driver are available in the current runtime. Selenium Manager may locate or manage a driver in supported environments; if startup fails, configure the driver and Chrome binary for the actual runtime rather than assuming a universal Colab path.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless=new")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
# Selenium Manager may resolve the driver when compatible with the runtime.
driver = webdriver.Chrome(options=options)
2. Navigate, wait for content, and capture the whole page
Use an explicit wait for a page condition that means the content you need is ready. The example below waits for the document body, allows a brief rendering pause, then captures beyond the viewport. Change the URL to the page you control or are authorized to capture.
from base64 import b64decode
from pathlib import Path
from selenium.webdriver.support.ui import WebDriverWait
url = "https://example.com"
driver.get(url)
# Wait until the document has loaded and has a body.
WebDriverWait(driver, 30).until(
lambda d: d.execute_script(
"return document.readyState === 'complete' && document.body !== null"
)
)
# Optional short pause for client-side rendering after document load.
driver.implicitly_wait(0)
driver.execute_script("return new Promise(resolve => setTimeout(resolve, 1000))")
result = driver.execute_cdp_cmd(
"Page.captureScreenshot",
{
"format": "png",
"captureBeyondViewport": True,
},
)
output_path = Path("/content/full_page.png")
output_path.write_bytes(b64decode(result["data"]))
print(f"Saved {output_path} ({output_path.stat().st_size:,} bytes)")
The CDP response’s data field is base64-encoded image content. The protocol supports PNG, JPEG, and WebP; PNG is the default. This example specifies PNG so the output extension and encoding agree. See the CDP Page protocol.
3. Make the image available outside the Colab runtime
A file under /content is in the hosted runtime, not durable storage. Download it during the session or copy it to storage you control. Colab VMs may be deleted after inactivity and have a maximum lifetime; check the Colab FAQ for current runtime details.
from google.colab import files
files.download("/content/full_page.png")
For a reusable notebook, keep the capture and download steps in separate cells. If the runtime restarts, rerun setup, recreate the browser, and repeat the capture; browser state and files in the prior VM may no longer exist.
4. Handle lazy-loaded and dynamic pages
captureBeyondViewport captures rendered content outside the current viewport. It does not guarantee that a site will load content whose own JavaScript waits for scrolling, interaction, or additional network requests. For those pages, prepare the page before capturing:
- Wait for a known content selector with
WebDriverWait, rather than relying only on a fixed sleep. - For scroll-triggered lazy loading, scroll down in increments and wait briefly between increments so the page can request and render more content; then return to the top if the capture method or page layout requires it.
- Click or dismiss overlays only when that interaction is appropriate and permitted for the target page.
- For infinite-scroll pages, decide on a stopping condition such as a known number of items or a page-end marker. Otherwise the page may keep growing and the image can become impractically large.
# Example preparation for scroll-triggered content. Adjust the pause and
# stopping condition for the site; this is not a guarantee every lazy loader
# will activate the same way.
previous_height = 0
for _ in range(20):
height = driver.execute_script("return document.body.scrollHeight")
if height == previous_height:
break
previous_height = height
driver.execute_script("window.scrollTo(0, arguments[0])", height)
driver.execute_script("return new Promise(resolve => setTimeout(resolve, 500))")
driver.execute_script("window.scrollTo(0, 0)")
5. Choose the right full-page method
| Browser or method | What it does | When to use it |
|---|---|---|
Chrome CDP via execute_cdp_cmd |
Calls Page.captureScreenshot; set captureBeyondViewport to request content beyond the viewport. |
Use when the Colab runtime is running Chrome and you need a full-page capture. |
Selenium save_screenshot() |
Saves the current browsing context or window image. | Use for a viewport screenshot; it is not a substitute for explicitly requesting CDP beyond-viewport capture. |
| Firefox full-page methods | Selenium’s Firefox driver documents get_full_page_screenshot_as_file() and save_full_page_screenshot(). |
Use when your environment runs Firefox and you want its documented full-page screenshot method. See Selenium Firefox WebDriver. |
For Chrome, the CDP path is the direct browser-specific route. Browser availability and setup in a hosted notebook remain runtime-dependent.
6. Screenshot format and practical limits
- Format: CDP supports PNG, JPEG, and WebP. PNG preserves crisp text and avoids lossy compression; JPEG or WebP may reduce file size when supported by the browser protocol and suitable for the use case.
- Page size: Very long pages can produce large images and use substantial browser memory. Consider whether a full-page image is necessary, or capture specific sections if the consumer can accept multiple images.
- Rendering: Wait for fonts, client-side rendering, and images that matter to your capture. A document reaching
readyState === 'complete'does not mean every application-specific request or lazy image has finished. - Reliability: Use explicit waits for site-specific conditions, keep the browser and driver compatible, and persist the output before the notebook runtime is lost.
- Cost: The Selenium approach uses a Colab runtime and browser resources. This guide makes no timing or performance guarantee; page complexity, image dimensions, browser startup, and runtime availability affect resource use.
7. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
SessionNotCreatedException or Chrome fails to start |
Chrome and ChromeDriver are missing or incompatible, or the runtime’s browser path differs from the example you copied. | Inspect the current runtime’s installed browser and driver, install compatible versions, and configure the actual binary path if needed. Do not assume a fixed Colab image. |
unknown command or CDP command error |
The active driver/browser combination does not expose the command as expected. | Confirm that the session is using Selenium’s Chromium driver with Chrome, update compatible Selenium/browser components, and check the CDP Page protocol for the command and parameters. |
| The image contains only the visible viewport | The code used ordinary save_screenshot(), or the beyond-viewport setting was omitted. |
Call Page.captureScreenshot with captureBeyondViewport: True, then decode the returned data. |
| Lower sections are blank or missing | The site loads them only after scrolling, waiting, or interaction. | Scroll to trigger lazy loading, wait for the relevant selector or image, and capture after the page has rendered the required sections. |
| Screenshot is unexpectedly short or the layout changes during capture | Content is still expanding, an animation is active, or an infinite list has not reached a stable state. | Wait for a stable site-specific condition, disable animation only if appropriate for your use, and set a deliberate stopping condition for infinite content. |
| The PNG is not available after a restart | The file was stored only in the temporary Colab VM. | Download it or copy it to durable storage before the runtime ends; rerun the notebook if the VM has already been deleted. |
| Notebook works for you but not a collaborator | Installed libraries, files, or VM state were not shared with the notebook. | Add setup and file-loading cells, as recommended by the Colab FAQ. |
8. Or skip the browser setup
If you need a screenshot without installing and maintaining Selenium and a browser in a notebook, ScreenshotNeo is a website screenshot API and MCP server for developers. Make one GET request with the page URL. See the ScreenshotNeo API documentation for request options.
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}`);
- Cookie banners are accepted like a visitor, and 60+ known consent platforms, newsletter popups, and chat widgets are removed before the shot; each step can be turned off.
- Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Response headers identify the page verdict and billing status.
- An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs.
- The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.
Create a free ScreenshotNeo account for 1,000 screenshots a month with no card.
9. FAQ
Can I run this in a Colab notebook without saving to disk?
The CDP command returns base64 image data in memory. Writing it to a file is useful for downloading or persisting it; you can also decode the value and pass the bytes to an image-processing library in the same cell.
Does CDP make a page load content that has not rendered?
No. It captures the rendered page area requested by the command. Site-specific lazy loading and interactive content may need to be triggered first.
Is the output a full-page PDF?
No. This flow writes a raster image. If you need a PDF, use a browser’s PDF workflow or a screenshot service that supports PDF output.
Will the notebook file remain available permanently?
No. A file in the Colab runtime is tied to that VM. Download it or copy it to storage you control before the runtime is deleted.


