ScreenshotNeo

BlogHow-to

How to Save Selenium Website Screenshots to Google Drive from Google Colab in India

Mount Google Drive in Colab, capture a Selenium screenshot, and save it reliably. Includes runnable code, troubleshooting, and a browser-free API option.

By the ScreenshotNeo team4 October 20268 min read

Direct answer: In Google Colab, mount Drive with drive.mount('/content/drive'), then pass a path under /content/drive/MyDrive/ to Selenium’s driver.save_screenshot(). The method saves the current browser window as PNG and returns False if an I/O error occurs, so check that value. The documented workflow is the same for readers in India; the sources reviewed do not describe a country-specific procedure. Google Colab’s data I/O notebook and Selenium’s Python API documentation describe these steps.

1. Mount Google Drive in Colab

Run this in a notebook cell. Colab prompts you to authorize access. The mounted folder lets notebook code read and write files in Drive, so only run notebook code you trust.

from google.colab import drive

drive.mount('/content/drive')

Your Drive files appear under /content/drive/MyDrive/. Create the output folder and check that it exists:

from pathlib import Path

output_dir = Path('/content/drive/MyDrive/selenium_screenshots')
output_dir.mkdir(parents=True, exist_ok=True)
print(output_dir)

2. Capture a page with Selenium and save the screenshot

The following cell assumes driver is an already initialized Selenium WebDriver. Navigate to the page, wait for the content you need, and save a PNG to the mounted Drive folder.

from pathlib import Path
from selenium.webdriver.support.ui import WebDriverWait

url = 'https://example.com'
driver.get(url)

# Wait for the document to finish loading. This does not guarantee that
# JavaScript-rendered content or lazy images are ready.
WebDriverWait(driver, 30).until(
    lambda d: d.execute_script('return document.readyState') == 'complete'
)

output_dir = Path('/content/drive/MyDrive/selenium_screenshots')
output_dir.mkdir(parents=True, exist_ok=True)
screenshot_path = output_dir / 'example-com.png'

saved = driver.save_screenshot(str(screenshot_path))
if not saved:
    raise IOError(f'Could not save screenshot to {screenshot_path}')

if not screenshot_path.exists() or screenshot_path.stat().st_size == 0:
    raise IOError(f'Screenshot is missing or empty: {screenshot_path}')

print(f'Saved {screenshot_path} ({screenshot_path.stat().st_size} bytes)')

Replace https://example.com with the page you need. Keep the .png extension: Selenium documents save_screenshot() as producing PNG output. This captures the current browser window, not necessarily the entire page.

Colab does not guarantee one particular browser installation or setup in every runtime. Initialize a WebDriver that works in your current runtime before running the capture cell. If you use a headless browser, make sure its configured viewport is large enough for the part of the page you need.

3. Make the capture repeatable

For multiple pages, give each output a distinct filename and keep the driver open across captures. A stable filename avoids overwriting earlier results; the example below uses a timestamp and a sanitized hostname.

from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlparse
from selenium.webdriver.support.ui import WebDriverWait

output_dir = Path('/content/drive/MyDrive/selenium_screenshots')
output_dir.mkdir(parents=True, exist_ok=True)

urls = [
    'https://example.com',
    'https://www.python.org',
]

for url in urls:
    driver.get(url)
    WebDriverWait(driver, 30).until(
        lambda d: d.execute_script('return document.readyState') == 'complete'
    )

    host = urlparse(url).netloc.replace(':', '_') or 'page'
    timestamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
    screenshot_path = output_dir / f'{host}-{timestamp}.png'

    if not driver.save_screenshot(str(screenshot_path)):
        raise IOError(f'Could not save screenshot to {screenshot_path}')
    if screenshot_path.stat().st_size == 0:
        raise IOError(f'Screenshot is empty: {screenshot_path}')

    print(f'Saved {screenshot_path}')

For pages that load content after the document is ready, wait for a page-specific element instead of relying only on document.readyState:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

WebDriverWait(driver, 30).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, 'main'))
)

Choose a selector that indicates the content you need is actually visible. A generic page load event may happen before a single-page app finishes rendering, an image loads, or an animation settles.

4. Understand the screenshot and storage choices

Choice Use it when Trade-off
Save directly to mounted Drive You need each screenshot to appear in Drive immediately. Drive operations depend on the mounted runtime and can be slow or quota-limited.
Save locally, then copy to Drive You are capturing many files and want fewer Drive writes. Local runtime storage is temporary; copy the files before the runtime ends.
PyDrive2 or Drive REST API Drive mounting is unsupported or an API-oriented workflow better fits your access needs. These require a different setup than writing to a mounted filesystem path.
Download to your computer You want a local download rather than a file stored in Drive. The file is not thereby saved in Drive.

Colab documents Drive mounting, PyDrive2 and Drive REST API options, and downloading runtime files. Its FAQ notes that mounted Drive operations rely on the runtime and that Drive I/O can be slow. It recommends reducing reads and writes to Drive for better performance. For a large batch, capturing to local runtime storage first and copying files to Drive in fewer operations follows that advice; it is a practical inference, not a documented guarantee.

Save locally and copy in fewer operations

from pathlib import Path
import shutil

local_dir = Path('/content/selenium_screenshots')
drive_dir = Path('/content/drive/MyDrive/selenium_screenshots')
local_dir.mkdir(parents=True, exist_ok=True)
drive_dir.mkdir(parents=True, exist_ok=True)

# Save captures to local_dir while the batch runs, for example:
# driver.save_screenshot(str(local_dir / 'page-001.png'))

# Copy the completed batch to Drive before the runtime ends.
for local_file in local_dir.glob('*.png'):
    destination = drive_dir / local_file.name
    shutil.copy2(local_file, destination)
    if not destination.exists() or destination.stat().st_size == 0:
        raise IOError(f'Copy failed or produced an empty file: {destination}')

For a small number of screenshots, direct writes are simpler. For either method, verify the output files in the Drive folder before ending the session.

5. Troubleshooting

Symptom Likely cause What to do
ModuleNotFoundError: No module named 'google.colab' The code is not running in a Colab notebook runtime. Run the mount cell in Colab. In another environment, use its supported Drive access method.
Mount authorization fails or Drive is not accessible Authorization, account access, or an organization policy may be blocking access. Rerun the mount cell and follow its authorization flow. If access remains blocked, check your account or ask your organization administrator.
OSError or save_screenshot() returns False The path may be invalid, Drive I/O may have failed, or a quota may have been reached. Check that Drive is mounted, the parent directory exists, the path is writable, and storage or quotas are available. Try saving to local runtime storage, then copy the file to Drive.
The screenshot is blank or shows a loading state The page may not have loaded the required content before capture, or navigation may have failed. Check driver.current_url and the page content. Wait for a specific visible element, and handle redirects, authentication, or errors before capturing.
Some images or content are missing Lazy-loaded images or JavaScript content may not be ready at document load completion. Wait for the relevant element or image to load. For a long page, scroll through the sections before capturing if that is appropriate for the page.
Screenshot is cropped save_screenshot() captures the current browser window. Increase the WebDriver window dimensions before capturing, or use a documented full-page technique supported by your browser setup.
Drive operations are very slow Drive storage may be far from the runtime, or many small reads and writes are taking place. Reduce Drive operations. Capture locally and copy files in fewer operations when producing a large batch.
Mounting is unsupported in Colab Enterprise Colab’s Drive mount implementation does not support Colab Enterprise. Use an API-based Drive workflow such as PyDrive2 or the Drive REST API as appropriate. See the Colab Drive implementation and Colab I/O notebook.

6. Performance, reliability, and cost

  • Performance: Browser navigation and page rendering usually determine capture time; writing to mounted Drive adds I/O. Google advises reducing Drive reads and writes. Batch local files and copy them in fewer operations if Drive I/O becomes a bottleneck.
  • Reliability: The mount is accessed through the Colab runtime. A local path such as /content/selenium_screenshots is runtime storage, so it should not be treated as persistent. Save to the mounted Drive path for Drive persistence and confirm the files exist there.
  • Errors: Check Selenium’s Boolean return value and file size. A successful browser capture does not by itself prove the intended page content appeared; inspect the page state when capture quality matters.
  • Cost: This method uses Selenium, Colab, and Google Drive. The research sources here do not establish pricing, quotas, or account limits for an individual reader. Check the terms and limits for the accounts you use rather than assuming unlimited runtime or storage.
  • India: The cited documentation describes a general workflow and does not establish different steps, availability, or organization policies for India. If access is blocked, check your account or organization administrator.

7. Or skip the browser setup

If your goal is a website screenshot rather than a Selenium browser session, ScreenshotNeo returns a screenshot or PDF from one API request. Its options include full-page capture, a CSS-selected element, viewport and device presets, waits, custom headers and cookies, and image format choices. See the ScreenshotNeo API documentation.

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', image));
  • Cookie and consent banners are accepted and removed before the shot; newsletter popups and chat widgets can also be removed.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are never billed. Response headers identify the page verdict and billing status.
  • An MCP server lets AI agents, including Claude and Cursor, use screenshot tools.
  • The Free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 screenshots.

Sign up for 1,000 free screenshots a month, with no card.

8. FAQ

Does this workflow change for users in India?

The official sources reviewed describe the same Colab mount-and-save process generally and do not specify a separate India workflow. Account or organization access rules may still affect your setup.

Does Selenium save a full-page image?

driver.save_screenshot() saves the current window. The result may not include content outside the visible browser area.

Can I save the screenshot as JPEG?

This Selenium method documents PNG output. Keep the filename extension as .png so it matches the file content.

What if I cannot mount Drive?

Colab lists PyDrive2 and the native Drive REST API as alternatives. Colab Enterprise does not support the mount implementation; use an appropriate API-based workflow there.