Take Website Screenshots With Python and Playwright

Real Python · Intermediate ·🔧 Backend Engineering ·1y ago

Key Takeaways

This video demonstrates how to use Playwright with Python to take automated screenshots of web elements, specifically capturing a screenshot of a specific HTML element and saving it as an image file. The video also covers using the __name__ == __main__ guard to run the script and saving the screenshot in a file.

Full Transcript

Currently, you're only getting the content of the H1 element as text, but later you actually want to have an image of code. So, next step is to actually get an image of an element with playright. Inside the take screenshot function, replace the line where you're currently calling the print function and passing in the text content of the element with actually taking a screenshot. You do so by calling the screenshot method. The screenshot method returns an image as bytes. So you need to save the bite somewhere, ideally in a file, but for now let's save it in a variable first. So at this point you're visiting the website, you're locating the H1 element and then you're taking a screenshot that you save in the screenshot bytes variable. After that you close the browser and that's okay for now. But after closing the browser, you actually want to save the screenshot by its content in an image file. For this, you're using a context manager again. And for now, you name the screenshot screenshot.png. Open it in the right binary mode using a variable name, for example, img for image. And then inside the context manager, you're writing the screenshot bytes variable into the image file. After saving the utos.py PI file, you need to run the take screenshot function again to save an image file. Now you could open a Python ripple again, but you can also use the if dunder name equals main idom in order to run the take screenshot function with our URL when you run the utils.py file directly. So let's do that. Underneath the function you can write the if condition if dunder name equals the string dunder main. Run take screenshot with the URL of our flask app. So now you can run the utils file directly and see if it takes a screenshot. Python utils.py. And once you hit enter, you see that it works a little bit because it takes a moment until you see your prompt again. And on the left side, you see that there is a screenshot.png file that playright created. If everything really worked as expected, the screenshot should contain basically the same content that we would see when we visit the page. So for that, let's first go to the browser again and check how our website looks right now. And then let's open the screenshot. And there you can see the content of the H1 element, which is our hello string now as an image. Isn't this cool? Well, I think it is cool. But let's play around with it a little bit. If you're not convinced yet, go to the app.py file and change hello to, for example, an emoji. save the file and visit the browser again to verify that the emoji is showing. And as you can see, we're still seeing the hello page. So that's good that we checked it because currently our flash server isn't restarting when we adjust something with the code. So we could stop the server and rerun it like before. And now when you reload the page, you see the emoji. Or you can run the server in debug mode which then automatically restarts the server when you change the code. So let's do that. Stop the server again and then add d-debug at the end of your python-m flask run command. And then you see that debug mode is on. And now if you change something in your app.py Pi file you see that the server is automatically restarting and when you go to the browser and reload it then the updates are already there. And also to be very clear here you don't have to have the browser open in order to make the screenshot. So if I close the browser and I'm in the app.py Pi file, I can still run the Python util script and it will still take a screenshot of the browser because you're using playrite in the background and I just had a browser open to verify that everything is looking like I want it to look. Once you run utils.py file, it takes a moment. It takes a screenshot. Let's see what's the content now. And there you have it. A waving smiley. Nice. If you zoom in, you might recognize that for me the emoji is a bit blurry. This could also be the case for you. Also, currently, we're overwriting the screenshots every time we're running the script. It would be nicer to actually create a collection of screenshots. So, the blurriness and overwriting the screenshot is something that we should tackle in the next lesson.

Original Description

Learn how to use Playwright with Python to take automated screenshots of web elements—no browser window required. In this video, you'll see how to: Capture a screenshot of a specific HTML element (like an H1 heading) Save it as an image file using Python Use __name__ == "__main__" to run your script from the command line Enable Flask debug mode to auto-reload your app when editing This is a clip from our course “Building a Code Image Generator With Python.” ▶ Watch the full course: realpython.com/courses/code-image-generator
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

Learn how to use Playwright with Python to take automated screenshots of web elements and save them as image files. The video covers using the __name__ == __main__ guard to run the script and saving the screenshot in a file.

Key Takeaways
  1. Visit a website using Playwright
  2. Locate a specific HTML element
  3. Take a screenshot of the element using the screenshot method
  4. Save the screenshot as an image file
  5. Use the __name__ == __main__ guard to run the script
  6. Run the script in debug mode to automatically restart the server when code changes are made
💡 You can use Playwright to take automated screenshots of web elements without having to open a browser window.

Related Reads

Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →