Package: shot-scraper-test
shot-scraperTools for taking automated screenshots of websitesFor background on this project seeshot-scraper: automated screenshots for documentation, built on Playwright.QuickstartTo get started without installing any software, use theshot-scraper-templatetemplate to create your own GitHub repository which takes screenshots of a page usingshot-scraper. SeeInstantly create a GitHub repository to take screenshots of a web pagefor details.DemosTheshot-scraper-demorepository uses this tool to capture recently spotted owls in El Granada, CA according tothis page, and to  generate an annotated screenshot illustrating a Datasette feature as describedin my blog.Ben Welsh built@newshomepages, a Twitter bot that usesshot-scraperand GitHub Actions to take screenshots of news website homepages and publish them to Twitter. The code for that lives inpalewire/news-homepages.scrape-hacker-news-by-domainusesshot-scraper javascriptto scrape a web page. SeeScraping web pages from the command-line with shot-scraperfor details of how this works.InstallationInstall this tool usingpip:pip install shot-scraperThis tool depends on Playwright, which first needs to install its own dedicated browser.Runshot-scraper installonce 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-1007Taking a screenshotTo take a screenshot of a web page and write it todatasette-io.pngrun this:shot-scraper https://datasette.io/If a file calleddatasette-io.pngalready exists the filenamedatasette-io.1.pngwill be used instead.You can use the-ooption to specify a filename:shot-scraper https://datasette.io/ -o datasette.pngUse-o -to write the PNG image to standard output:shot-scraper https://datasette.io/ -o - > datasette.pngIf you omit the protocolhttp://will be added automatically, and any redirects will be followed:shot-scraper datasette.io -o datasette.pngAdjusting the browser width and heightThe browser window used to take the screenshots defaults to 1280px wide and 780px tall.You can adjust these with the--widthand--heightoptions:shot-scraper https://datasette.io/ -o small.png --width 400 --height 800If you provide both options, the resulting screenshot will be of that size. If you omit--heighta full page length screenshot will be produced (the default).Screenshotting a specific area with CSS selectorsTo take a screenshot of a specific element on the page, use--selectoror-swith its CSS selector:shot-scraper https://simonwillison.net/ -s '#bighead'When using--selectorthe 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--selectormultiple 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.pngYou can add--padding 20to add 20px of padding around the elements when the shot is taken.Adding a delaySometimes a page will not have completely loaded before a screenshot is taken. You can use--wait Xto wait the specified number of milliseconds after the page load event has fired before taking the screenshot:shot-scraper https://simonwillison.net/ --wait 2000Executing custom JavaScriptYou 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--javascriptoption:shot-scraper https://simonwillison.net/ \
  -o simonwillison-pink.png \
  --javascript "document.body.style.backgroundColor = 'pink';"Using JPEGs instead of PNGsScreenshots default to PNG. You can save as a JPEG by specifying a-ofilename that ends with.jpg.You can also use--quality Xto 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.jpgRetina imagesThe--retinaoption sets a device scale factor of 2. This means that an image will have its resolution effectively doubled, emulating the display of images onretinaor higher pixel density screens.shot-scraper https://simonwillison.net/ -o simon.png \
  --width 400 --height 600 --retinaThis example will produce an image that is 800px wide and 1200px high.Interacting with the pageSometimes it's useful to be able to manually interact with a page before the screenshot is captured.Add the--interactiveoption 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 --interactiveThis 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 filesYou can pass the path to an HTML file on disk to take a screenshot of that rendered file:shot-scraper index.html -o index.pngCSS and images referenced from that file using relative paths will also be included.shot-scraper shot --helpFull--helpfor 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 authenticationIf 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 theshot-scraper authcommand:shot-scraper auth https://datasette-auth-passwords-demo.datasette.io/-/login auth.json(For this demo, use username =rootand 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 theshot-scrapercommand-line prompt. The browser will close and the authentication credentials (usually cookies) for that browser session will be written out to theauth.jsonfile.To take authenticated screenshots you can then use the-aor--authoptions to point to the JSON file that you created:shot-scraper https://datasette-auth-passwords-demo.datasette.io/ \
  -a auth.json -o authed.pngTaking multiple screenshotsYou can configure multiple screenshots using a YAML file. Create a file calledshots.ymlthat looks like this:url:http://www.example.com/-output:w3c.org.pngurl:https://www.w3.org/Then run the tool like so:shot-scraper multi shots.ymlThis will create two image files,www-example-com.pngandw3c.org.png, containing screenshots of those two URLs.You can seturl:to a path to a file on disk as well:-output:index.pngurl:index.htmlUse--retinato take all screenshots at retina resolution instead, doubling the dimensions of the files:shot-scraper multi shots.yml --retinaTo take a screenshot of just the area of a page defined by a CSS selector, addselectorto the YAML block:-output:bighead.pngurl:https://simonwillison.net/selector:"#bighead"You can pass more than one selector using aselectors:list. You can also usepadding:to specify additional padding:-output:bighead-multi-selector.pngurl:https://simonwillison.net/selectors:-"#bighead"-.overbandpadding:20To execute JavaScript after the page has loaded but before the screenshot is taken, add ajavascriptkey:-output:bighead-pink.pngurl:https://simonwillison.net/selector:"#bighead"javascript:|document.body.style.backgroundColor = 'pink'You can include desiredheight,width,qualityandwaitoptions on each item as well:-output:simon-narrow.jpgurl:https://simonwillison.net/width:400height:800quality:80wait:500Full--helpfor 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 PDFTheshot-scraper pdfcommand saves a PDF version of a web page - the equivalent of usingPrint -> Save to PDFin Chromium.shot-scraper pdf https://datasette.io/This will save todatasette-io.pdf. You can use-oto specify a filename:shot-scraper pdf https://datasette.io/tutorials/learn-sql \
  -o learn-sql.pdfFull--helpfor 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.Scraping pages using JavaScriptTheshot-scraper javascriptcommand can be used to execute JavaScript directly against a page and return the result as JSON.This command doesn't produce a screenshot, but has interesting applications for scraping.To retrieve a string title of a document:shot-scraper javascript https://datasette.io/ "document.title"This returns a JSON string:"Datasette: An open source multi-tool for exploring and publishing data"To return a JSON object, wrap an object literal in parenthesis:shot-scraper javascript https://datasette.io/ "({
  title: document.title,
  tagline: document.querySelector('.tagline').innerText
})"This returns:{"title":"Datasette: An open source multi-tool for exploring and publishing data","tagline":"An open source multi-tool for exploring and publishing data"}To use functions such assetInterval(), for example if you need to delay the shot for a second to allow an animation to finish running, return a promise:shot-scraper javascript datasette.io "
new Promise(done => setInterval(
  () => {
    done({
      title: document.title,
      tagline: document.querySelector('.tagline').innerText
    });
  }, 1000
));"You can also save JavaScript to a file and execute it like this:shot-scraper javascript datasette.io -i script.jsOr read it from standard input like this:echo "document.title" | shot-scraper javascript datasette.ioHandling JavaScript errorsIf a JavaScript error occurs, a stack trace will be written to standard error and the tool will terminate with an exit code of 1.This can be used to run JavaScript tests in continuous integration environments, by taking advantage of thethrow "error message"JavaScript statement.This exampleuses GitHub Actions:-name:Test page titlerun:|-shot-scraper javascript datasette.io "if (document.title != 'Datasette') {throw 'Wrong title detected';}"Full--helpfor this command:Usage: shot-scraper javascript [OPTIONS] URL [JAVASCRIPT]

  Execute JavaScript against the page and return the result as JSON

  Usage:

      shot-scraper javascript https://datasette.io/ "document.title"

  To return a JSON object, use this:

      "({title: document.title, location: document.location})"

  To use setInterval() or similar, pass a promise:

      "new Promise(done => setInterval(
        () => {
          done({
            title: document.title,
            h2: document.querySelector('h2').innerHTML
          });
        }, 1000
      ));"

  If a JavaScript error occurs an exit code of 1 will be returned.

Options:
  -i, --input FILENAME   Read input JavaScript from this file
  -a, --auth FILENAME    Path to JSON authentication context file
  -o, --output FILENAME  Save output JSON to this file
  -h, --help             Show this message and exit.Dumping out an accessibility treeTheshot-scraper accessibilitycommand dumps out the Chromium accessibility tree for the provided URL, as JSON:shot-scraper accessibility https://datasette.io/Use-o filename.jsonto write the output to a file instead of displaying it.Add--javascript SCRIPTto execute custom JavaScript before taking the snapshot.Full--helpfor 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 JavaScriptIf you are using the--javascriptoption 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 thispink arrow example.This code hides any element with a[data-ad-rendered]attribute and the element withid="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:newPromise(takeShot=>{// Your code goes here// ...setTimeout(()=>{// Resolving the promise takes the shottakeShot();},1000);});If your custom code defines aPromise,shot-scraperwill wait for that promise to complete before taking the screenshot. Here the screenshot does not occur until thetakeShot()function is called.DevelopmentTo contribute to this tool, first checkout the code. Then create a new virtual environment:cd shot-scraper
python -m venv venv
source venv/bin/activateOr if you are usingpipenv:pipenv shellNow install the dependencies and test dependencies:pip install -e '.[test]'To run the tests:pytestSome of the tests exercise the CLI utility directly. Run those like so:tests/run_examples.sh