When web scraping, we might want to collect page screenshots or peek into what our headless browsers are seeing for debugging. With Selenium, to take screenshots
save_screenshot() method can be used to capture the whole page or a specific area:
from selenium import webdriver driver = webdriver.Chrome() driver.get("https://httpbin.org/html") # For whole page # we can save directly to a given filename driver.save_screenshot('screenshot.png') # or retrieve to python objects screenshot_png_bytes = driver.get_screenshot_as_png() screenshot_base64_string = driver.get_screenshot_as_base64() # For specific element: from selenium.webdriver.common.by import By element = driver.find_element(By.CSS_SELECTOR, 'p') element.screenshot('just-the-paragraph.png') driver.close()
⚠ Note that when scraping dynamic pages screenshot can be captured before page is fully loaded. For more see How to wait for page to load in Selenium?