Last modified: Nov 10, 2023 By Alexander Williams
Exploring Different Ways to Capture Web Page Screenshots in Python
Using Selenium and WebDriver
# Import necessary library
from selenium import webdriver
# URL of the web page to capture
url = "https://example.com"
# Initialize WebDriver (make sure to have the appropriate driver installed)
driver = webdriver.Chrome()
# Open the web page
driver.get(url)
# Capture screenshot and save it
driver.save_screenshot("screenshot.png")
# Close the browser
driver.quit()
Output:
# No specific output, the screenshot is saved as screenshot.png
Using Pyppeteer (Headless Chrome with Python)
# Import necessary library
from pyppeteer import launch
# Async function to capture screenshot
async def capture_screenshot(url):
# Launch a headless browser
browser = await launch()
# Create a new page
page = await browser.newPage()
# Navigate to the specified URL
await page.goto(url)
# Capture screenshot and save it
await page.screenshot({'path': 'screenshot.png'})
# Close the browser
await browser.close()
# Call the async function with the URL
await capture_screenshot("https://example.com")
Output:
# No specific output, the screenshot is saved as screenshot.png
Using Requests and PIL (Python Imaging Library)
# Import necessary libraries
import requests
from PIL import Image
from io import BytesIO
# URL of the web page to capture
url = "https://example.com"
# Make a request to the URL
response = requests.get(url)
# Open the image using PIL
img = Image.open(BytesIO(response.content))
# Save the image
img.save("screenshot.png")
Output:
# No specific output, the screenshot is saved as screenshot.png
Using Selenium and Full Page Screenshot
# Import necessary library
from selenium import webdriver
# URL of the web page to capture
url = "https://example.com"
# Initialize WebDriver (make sure to have the appropriate driver installed)
driver = webdriver.Chrome()
# Open the web page
driver.get(url)
# Find the body element and capture a full-page screenshot
screenshot = driver.find_element_by_tag_name("body")
screenshot.screenshot("full_page_screenshot.png")
# Close the browser
driver.quit()
Output:
# No specific output, the full page screenshot is saved as full_page_screenshot.png
Using pyautogui for Full Desktop Screenshot
# Import necessary library
import pyautogui
# Capture a screenshot of the entire desktop
screenshot = pyautogui.screenshot()
# Save the screenshot
screenshot.save("desktop_screenshot.png")
Output:
# No specific output, the desktop screenshot is saved as desktop_screenshot.png