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