Tools for taking automated screenshots of websites
Project description
shot-scraper
Tools for taking automated screenshots of websites
For background on this project see shot-scraper: automated screenshots for documentation, built on Playwright.
Demos
- The shot-scraper-demo repository uses this tool to capture recently spotted owls in El Granada, CA according to this page, and to generate an annotated screenshot illustrating a Datasette feature as described in my blog.
- Ben Welsh built @newshomepages, a Twitter bot that uses
shot-scraper
and GitHub Actions to take screenshots of news website homepages and publish them to Twitter. The code for that lives in palewire/news-homepages.
Installation
Install this tool using pip
:
pip install shot-scraper
This tool depends on Playwright, which first needs to install its own dedicated browser.
Run shot-scraper install
once to install that:
% shot-scraper install
Downloading Playwright build of chromium v965416 - 117.2 Mb [====================] 100% 0.0s
Playwright build of chromium v965416 downloaded to /Users/simon/Library/Caches/ms-playwright/chromium-965416
Downloading Playwright build of ffmpeg v1007 - 1.1 Mb [====================] 100% 0.0s
Playwright build of ffmpeg v1007 downloaded to /Users/simon/Library/Caches/ms-playwright/ffmpeg-1007
Taking a screenshot
To take a screenshot of a web page and write it to datasette-io.png
run this:
shot-scraper https://datasette.io/
If a file called datasette-io.png
already exists the filename datasette-io.1.png
will be used instead.
You can use the -o
option to specify a filename:
shot-scraper https://datasette.io/ -o datasette.png
Use -o -
to write the PNG image to standard output:
shot-scraper https://datasette.io/ -o - > datasette.png
If you omit the protocol http://
will be added automatically, and any redirects will be followed:
shot-scraper datasette.io -o datasette.png
Adjusting the browser width and height
The browser window used to take the screenshots defaults to 1280px wide and 780px tall.
You can adjust these with the --width
and --height
options:
shot-scraper https://datasette.io/ -o small.png --width 400 --height 800
If you provide both options, the resulting screenshot will be of that size. If you omit --height
a full page length screenshot will be produced (the default).
Screenshotting a specific area with CSS selectors
To take a screenshot of a specific element on the page, use --selector
or -s
with its CSS selector:
shot-scraper https://simonwillison.net/ -s '#bighead'
When using --selector
the height and width, if provided, will set the size of the browser window when the page is loaded but the resulting screenshot will still be the same dimensions as the element on the page.
You can pass --selector
multiple times. The resulting screenshot will cover the smallest area of the page that contains all of the elements you specified, for example:
shot-scraper https://simonwillison.net/ \
-s '#bighead' -s .overband \
-o bighead-multi-selector.png
You can add --padding 20
to add 20px of padding around the elements when the shot is taken.
Adding a delay
Sometimes a page will not have completely loaded before a screenshot is taken. You can use --wait X
to wait the specified number of milliseconds after the page load event has fired before taking the screenshot:
shot-scraper https://simonwillison.net/ --wait 2000
Executing custom JavaScript
You can use custom JavaScript to modify the page after it has loaded (after the 'onload' event has fired) but before the screenshot is taken using the --javascript
option:
shot-scraper https://simonwillison.net/ \
-o simonwillison-pink.png \
--javascript "document.body.style.backgroundColor = 'pink';"
Using JPEGs instead of PNGs
Screenshots default to PNG. You can save as a JPEG by specifying a -o
filename that ends with .jpg
.
You can also use --quality X
to save as a JPEG with the specified quality, in order to reduce the filesize. 80 is a good value to use here:
shot-scraper https://simonwillison.net/ \
-h 800 -o simonwillison.jpg --quality 80
% ls -lah simonwillison.jpg
-rw-r--r--@ 1 simon staff 168K Mar 9 13:53 simonwillison.jpg
Retina images
The --retina
option sets a device scale factor of 2. This means that an image will have its resolution effectively doubled, emulating the display of images on retina or higher pixel density screens.
shot-scraper https://simonwillison.net/ -o simon.png \
--width 400 --height 600 --retina
This example will produce an image that is 800px wide and 1200px high.
Interacting with the page
Sometimes it's useful to be able to manually interact with a page before the screenshot is captured.
Add the --interactive
option to open a browser window that you can interact with. Then hit <enter>
in the terminal when you are ready to take the shot and close the window.
shot-scraper https://simonwillison.net/ -o after-interaction.png \
--height 800 --interactive
This will output:
Hit <enter> to take the shot and close the browser window:
# And after you hit <enter>...
Screenshot of 'https://simonwillison.net/' written to 'after-interaction.png'
Taking screenshots of local HTML files
You can pass the path to an HTML file on disk to take a screenshot of that rendered file:
shot-scraper index.html -o index.png
CSS and images referenced from that file using relative paths will also be included.
shot-scraper shot --help
Full --help
for this command:
Usage: shot-scraper shot [OPTIONS] URL
Take a single screenshot of a page or portion of a page.
Usage:
shot-scraper www.example.com
This will write the screenshot to www-example-com.png
Use "-o" to write to a specific file:
shot-scraper https://www.example.com/ -o example.png
You can also pass a path to a local file on disk:
shot-scraper index.html -o index.png
Using "-o -" will output to standard out:
shot-scraper https://www.example.com/ -o - > example.png
Use -s to take a screenshot of one area of the page, identified using one or
more CSS selectors:
shot-scraper https://simonwillison.net -s '#bighead'
Options:
-a, --auth FILENAME Path to JSON authentication context file
-w, --width INTEGER Width of browser window, defaults to 1280
-h, --height INTEGER Height of browser window and shot - defaults to the
full height of the page
-o, --output FILE
-s, --selector TEXT Take shot of first element matching this CSS selector
-p, --padding INTEGER When using selectors, add this much padding in pixels
-j, --javascript TEXT Execute this JS prior to taking the shot
--retina Use device scale factor of 2
--quality INTEGER Save as JPEG with this quality, e.g. 80
--wait INTEGER Wait this many milliseconds before taking the
screenshot
-i, --interactive Interact with the page in a browser before taking the
shot
--devtools Interact mode with developer tools
--help Show this message and exit.
Websites that need authentication
If you want to take screnshots of a site that has some form of authentication, you will first need to authenticate with that website manually.
You can do that using the shot-scraper auth
command:
shot-scraper auth https://datasette-auth-passwords-demo.datasette.io/-/login auth.json
(For this demo, use username = root
and password = password!
)
This will open a browser window on your computer showing the page you specified.
You can then sign in using that browser window - including 2FA or CAPTCHAs or other more complex form of authentication.
When you are finished, hit <enter>
at the shot-scraper
command-line prompt. The browser will close and the authentication credentials (usually cookies) for that browser session will be written out to the auth.json
file.
To take authenticated screenshots you can then use the -a
or --auth
options to point to the JSON file that you created:
shot-scraper https://datasette-auth-passwords-demo.datasette.io/ \
-a auth.json -o authed.png
Taking multiple screenshots
You can configure multiple screenshots using a YAML file. Create a file called shots.yml
that looks like this:
- output: example.com.png
url: http://www.example.com/
- output: w3c.org.png
url: https://www.w3.org/
Then run the tool like so:
shot-scraper multi shots.yml
This will create two image files, example.com.png
and w3c.org.png
, containing screenshots of those two URLs.
You can set url:
to a path to a file on disk as well:
- output: index.png
url: index.html
Use --retina
to take all screenshots at retina resolution instead, doubling the dimensions of the files:
shot-scraper multi shots.yml --retina
To take a screenshot of just the area of a page defined by a CSS selector, add selector
to the YAML block:
- output: bighead.png
url: https://simonwillison.net/
selector: "#bighead"
You can pass more than one selector using a selectors:
list. You can also use padding:
to specify additional padding:
- output: bighead-multi-selector.png
url: https://simonwillison.net/
selectors:
- "#bighead"
- .overband
padding: 20
To execute JavaScript after the page has loaded but before the screenshot is taken, add a javascript
key:
- output: bighead-pink.png
url: https://simonwillison.net/
selector: "#bighead"
javascript: |
document.body.style.backgroundColor = 'pink'
You can include desired height
, width
, quality
and wait
options on each item as well:
- output: simon-narrow.jpg
url: https://simonwillison.net/
width: 400
height: 800
quality: 80
wait: 500
Full --help
for this command:
Usage: shot-scraper multi [OPTIONS] CONFIG
Take multiple screenshots, defined by a YAML file
Usage:
shot-scraper multi config.yml
Where config.yml contains configuration like this:
- output: example.png
url: http://www.example.com/
Options:
-a, --auth FILENAME Path to JSON authentication context file
--retina Use device scale factor of 2
-h, --help Show this message and exit.
Saving a web page to PDF
The shot-scraper pdf
command saves a PDF version of a web page - the equivalent of using Print -> Save to PDF
in Chromium.
shot-scraper pdf https://datasette.io/
This will save to datasette-io.pdf
. You can use -o
to specify a filename:
shot-scraper pdf https://datasette.io/tutorials/learn-sql \
-o learn-sql.pdf
Full --help
for this command:
Usage: shot-scraper pdf [OPTIONS] URL
Create a PDF of the specified page
Usage:
shot-scraper pdf https://datasette.io/
Use -o to specify a filename:
shot-scarper pdf https://datasette.io/ -o datasette.pdf
Options:
-a, --auth FILENAME Path to JSON authentication context file
-o, --output FILE
-j, --javascript TEXT Execute this JS prior to creating the PDF
--wait INTEGER Wait this many milliseconds before taking the
screenshot
--media-screen Use screen rather than print styles
--landscape Use landscape orientation
-h, --help Show this message and exit.
Dumping out an accessibility tree
The shot-scraper accessibility
command dumps out the Chromium accessibility tree for the provided URL, as JSON:
shot-scraper accessibility https://datasette.io/
Use -o filename.json
to write the output to a file instead of displaying it.
Add --javascript SCRIPT
to execute custom JavaScript before taking the snapshot.
Full --help
for this command:
Usage: shot-scraper accessibility [OPTIONS] URL
Dump the Chromium accessibility tree for the specifed page
Usage:
shot-scraper accessibility https://datasette.io/
Options:
-a, --auth FILENAME Path to JSON authentication context file
-o, --output FILENAME
-j, --javascript TEXT Execute this JS prior to taking the snapshot
-h, --help Show this message and exit.
Tips for executing JavaScript
If you are using the --javascript
option to execute code, that code will be executed after the page load event has fired but before the screenshot is taken.
You can use that code to do things like hide or remove specific page elements, click on links to open menus, or even add annotations to the page such as this pink arrow example.
This code hides any element with a [data-ad-rendered]
attribute and the element with id="ensNotifyBanner"
:
document.querySelectorAll(
'[data-ad-rendered],#ensNotifyBanner'
).forEach(el => el.style.display = 'none')
You can execute that like so:
shot-scraper https://www.latimes.com/ -o latimes.png --javascript "
document.querySelectorAll(
'[data-ad-rendered],#ensNotifyBanner'
).forEach(el => el.style.display = 'none')
"
In some cases you may need to add a pause that executes during your custom JavaScript before the screenshot is taken - for example if you click on a button that triggers a short fading animation.
You can do that using the following pattern:
new Promise(takeShot => {
// Your code goes here
// ...
setTimeout(() => {
// Resolving the promise takes the shot
takeShot();
}, 1000);
});
If your custom code defines a Promise
, shot-scraper
will wait for that promise to complete before taking the screenshot. Here the screenshot does not occur until the takeShot()
function is called.
Development
To contribute to this tool, first checkout the code. Then create a new virtual environment:
cd shot-scraper
python -m venv venv
source venv/bin/activate
Or if you are using pipenv
:
pipenv shell
Now install the dependencies and test dependencies:
pip install -e '.[test]'
To run the tests:
pytest
Some of the tests exercise the CLI utility directly. Run those like so:
tests/run_examples.sh
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file shot-scraper-0.8.tar.gz
.
File metadata
- Download URL: shot-scraper-0.8.tar.gz
- Upload date:
- Size: 18.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/34.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.10.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 984b751b9ce9851a0d3d0969b0acd479daaf3b229f446c861a1e12e6f469cc77 |
|
MD5 | 813719297f97433be306dda7f7dfd186 |
|
BLAKE2b-256 | 00ffad107e0b03f107304739a3deb4a2d4485cd6ed702a8a86f089ba7f9850f4 |
File details
Details for the file shot_scraper-0.8-py3-none-any.whl
.
File metadata
- Download URL: shot_scraper-0.8-py3-none-any.whl
- Upload date:
- Size: 15.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/34.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.11.2 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.10.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 921995ebee2fef379ec0a9081adf87bbe09ec7ce2b9af691c9fd1830b9c22188 |
|
MD5 | 83eaba6cf9e3f8b8b8312adddc0765f7 |
|
BLAKE2b-256 | 2f49b701c4938717b2aa8dcd63f549d32c32e585242d7494a7be947d8f7246b1 |